删除字符串中的空格不起作用

时间:2015-11-08 10:58:19

标签: string swift

我正在尝试删除<?php var_dump(searchPage("http://google.com", "Tacos")); //False var_dump(searchPage("http://google.com", "Google")); //True function searchPage($url, $string){ $input = file_get_contents($url); if (strpos($input,$string) !== false) { return true; }else{ return false; } } ?> 中的空格,这些是联系人应用中的电话号码。

我的代码适用于大多数数字,但对于2,它不起作用。它不能识别空间,即使它们的格式与其他格式完全相同。

例如:Strings然后是y = +49 999 99999999,但它应该是phonenumber = 0 999 99999999

099999999999

1 个答案:

答案 0 :(得分:1)

看起来它正在发挥作用。

您的代码

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:"")