4

i'm trying to remove white spaces and some characters from a string, please check my code below

// giving phoneString = +39 333 3333333
var phoneString = ABMultiValueCopyValueAtIndex(phone, indexPhone).takeRetainedValue() as! String

// Remove spaces from string
phoneString = phoneString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

// Remove +39 if exist
if phoneString.rangeOfString("+39") != nil{
    phoneString = phoneString.stringByReplacingOccurrencesOfString("\0", withString: "+39", options: NSStringCompareOptions.LiteralSearch, range: nil)
}

print(phoneString) // output +39 333 3333333

it seems like all the changes has no effect over my string, why this happen?

EDIT @V S

screen

EDIT 2:

I tried to convert my string in utf 8, check the result:

43 51 57 194 160 51 51 51 194 160 51 51 51 51 51 51 51

where:

43 = +
51 = 3
57 = 9
160 = space
194 = wtf?!? is this?

9 Answers 9

6

what do you try to do is

// your input string
let str = "+39 333 3333333"

let arr = str.characters.split(" ").map(String.init) // ["+39", "333", "3333333"]
// remove country code and reconstruct the rest as one string without whitespaces
let str2 = arr.dropFirst().joinWithSeparator("") // "3333333333"

to filter out country code, only if exists (as Eendje asks)

let str = "+39 123 456789"
let arr = str.characters.split(" ").map(String.init)
let str3 = arr.filter { !$0.hasPrefix("+") }.joinWithSeparator("") // "123456789"

UPDATE, based on your update. 160 represents no-breakable space. just modify next line in my code

let arr = str.characters.split{" \u{00A0}".characters.contains($0)}.map(String.init)

there is " \u{00A0}".characters.contains($0) expression where you can extend the string to as much whitespace characters, as you need. 160 is \u{00A0} see details here.

Update for Swift 4

String.characters is deprecated. So the correct answer would now be

// your input string
let str = "+39 333 3333333"

let arr = str.components(separatedBy: .whitespaces) // ["+39", "333", "3333333"]
// remove country code and reconstruct the rest as one string without whitespaces
let str2 = arr.dropFirst().joined() // "3333333333"
Sign up to request clarification or add additional context in comments.

9 Comments

What if the string doesn't contain "+39"? :)
@Mono.WTF is this, what you are looking for?
@Mono.WTF 160 represents unicode no-break space .... OK, I see now your trouble, will update my answer in few minutes :-)
@Mono.WTF sometimes we do not see the forest for the trees , it becomes :-)
can anyone tell why it doesn't replace the whitespace in the first place?
|
4

Swift 3 / Swift 4

let withoutSpaces = phoneNumber.replacingOccurrences(of: "\\s", with: "", options: .regularExpression)

Comments

3

Firstly, stringByTrimmingCharactersInSet only trims the string - i.e. removes leading & trailing spaces - you need to use stringByReplacingOccurrencesOfString replacing " " with "".

Secondly, your parameters on stringByReplacingOccurrencesOfString for the country code are the wrong way round.

Thirdly, "\0" is not what you want- that's ASCII null, not zero.

Comments

3

Swift 5

//MARK:- 3 ways to resolve it
var tempphone = "0345 55500 93"

//MARK:- No 1
tempphone = tempphone.replacingOccurrences(of: " ", with: "")

//MARK:- No 2
tempphone = tempphone.replacingOccurrences(of: "\\s", with: "", options: .regularExpression)

//MARK:- No 3
tempphone = tempphone.trimmingCharacters(in: .whitespaces)

Comments

1
phoneString = phoneString.stringByReplacingOccurrencesOfString("+39", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)


phoneString = phoneString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

3 Comments

@Mono.WTF, Check it.
same output, nothing changes
Can I see Log, print phoneString, before first line, after first line and last. and add Screenshot,
1

Try this. This has worked for me:

if phoneString.rangeOfString("+39") != nil{
            freshString = phoneString.stringByReplacingOccurrencesOfString("\0", withString: "+39", options: NSStringCompareOptions.LiteralSearch, range: nil)
        }

        var strings = freshString.componentsSeparatedByString(" ") as NSArray
        var finalString = strings.componentsJoinedByString("")
        //outputs +393333333333

Comments

1

You can use this replace the whitespace

phoneNumber.replacingOccurrences(of: "\u{00A0}", with: "")

Comments

0
let trimmedPhoneString = String(phoneString).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

To Remove +39 if exist, you can use stringByReplacingOccurrencesOfString instead

2 Comments

same output, nothing changes
Dude, stringByTrimmingCharactersInSet can trim the trailing or leading white spaces if any. check the apple docs. As i said you can use stringByReplacingOccurrencesOfString
0
var phoneString = "+39 333 3333333"
phoneString = phoneString.stringByReplacingOccurrencesOfString(" ", withString:"")
if phoneString.rangeOfString("+39") != nil
{
    phoneString = phoneString.stringByReplacingOccurrencesOfString("+39", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
}
print(phoneString) // output 3333333333

1 Comment

my output is: " 333 3333333"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.