我正在尝试删除 Strings
中的空格,它们是联系人应用中的电话号码。
我的代码对于大多数数字都可以正常工作,但对于 2 它不起作用。它无法识别空格,即使它们的格式与其他空格完全相同。
例如:如果 y = +49 999 99999999
那么 phonenumber = 0 999 99999999
,但它应该是 099999999999
。
let x = number[i].value as! CNPhoneNumber
let y = x.stringValue
// let toArray = y.componentsSeparatedByString(" ")
// let string = toArray.joinWithSeparator("")
var o = y.stringByReplacingOccurrencesOfString("-", withString: "")
o = o.stringByReplacingOccurrencesOfString("+49", withString: "0")
o = o.stringByReplacingOccurrencesOfString("(", withString: "")
o = o.stringByReplacingOccurrencesOfString(")", withString: "")
o = o.stringByReplacingOccurrencesOfString(" ", withString: "")
phonenumber = o
最佳答案
看起来它正在工作。
你的代码
let y = "+49 999 99999999"
var o = y.stringByReplacingOccurrencesOfString("-", withString: "")
o = o.stringByReplacingOccurrencesOfString("+49", withString: "0")
o = o.stringByReplacingOccurrencesOfString("(", withString: "")
o = o.stringByReplacingOccurrencesOfString(")", withString: "")
o = o.stringByReplacingOccurrencesOfString(" ", withString: "")
print(o, terminator:"")
实际打印:
099999999999
变量phonenumber
的类型是什么?也许这就是您看到添加了 2 个空格的原因。
更新
由于问题似乎与错误的 ascii 值有关,您可以应用相反的方法。现在您正在指定要删除的内容,请尝试指定要保留的内容。
let digits : Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
let phoneNumberWithPrefixAndSpaces = "+49 157 77859770"
let phoneNumbersWithSpaces = phoneNumberWithPrefixAndSpaces.stringByReplacingOccurrencesOfString("+49", withString: "0")
// only digits will "survive" to the next instruction
var phoneNumber = String(phoneNumbersWithSpaces.characters.filter { digits.contains($0) })
print(phoneNumber, terminator:"")
关于string - 删除字符串中的空格不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33593187/