Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Remove white spaces from string doesn't work

Tags:

xcode

ios

swift

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?
like image 720
Mono.WTF Avatar asked Dec 04 '22 01:12

Mono.WTF


1 Answers

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"
like image 78
user3441734 Avatar answered Dec 06 '22 15:12

user3441734