arrays - 消除数组中的空格,它不能快速工作

标签 arrays swift

我从矩阵联系人中获取号码,每个联系人都有一个人员号码,但是我的问题是我想要原始号码,以便可以与另一个矩阵匹配。

       for a in contacts 

{
        let content: String = a.phone

        let result1 = content.stringByReplacingOccurrencesOfString("(", withString:"")
        let result2 = result1.stringByReplacingOccurrencesOfString(")", withString:"")
        let result3 = result2.stringByReplacingOccurrencesOfString("-", withString:"")
        let result4 = result3.replace(" ", replacement: "")




        println(result4)


       // newNames.append(result4)
      //contador=contador+1
    }
   //result[555 555,999 3188,999 1]

所以不是消除空格为什么?,为什么如果其他条件很好的话,我也使用:

let result4 = result3.stringByReplacingOccurrencesOfString(" ", withString: "") 

为什么它不起作用?

//结果[555 555,999 3188,999 1]

最佳答案

您正在使用不同的 API,replace()

改用工作 API stringByReplacingOccurrencesOfString()

链接

请注意,您可以在 Swift 中进行链接,这要优雅得多。

let cleanNumber = content
  .stringByReplacingOccurrencesOfString("(", withString:"")
  .stringByReplacingOccurrencesOfString(")", withString:"")
  .stringByReplacingOccurrencesOfString("-", withString:"")
  .stringByReplacingOccurrencesOfString(" ", withString:"")

过滤器和映射

此外,请注意更简洁的 filtermap API。

let content = "(459) 333-4938"
let cleanNumber = content.characters.filter {
    ![" ", "-", "(", ")"].contains($0)
}.map { String($0) }.joinWithSeparator("")
// "4593334938"

NSCharacterSet

还有旧的 NSCharacterSet 技巧:

let illegal = NSCharacterSet(charactersInString: "1234567890").invertedSet
let cleanNumber = content
   .componentsSeparatedByCharactersInSet(illegal)
   .joinWithSeparator("")
// "4593334938"

关于arrays - 消除数组中的空格,它不能快速工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32591364/

相关文章:

swift - 旋转 Swift 数组

c - 扩展动态分配的指针数组

ios - Objective-C 应用程序中缺少 Swift 框架中的 IBOutlet 属性

json - 需要一些帮助在 POST 请求后使用 JSON 数据填充 tableview

swift - MacOS中如何使用Process类执行需要输入密码的命令

iOS在动画过程中显示标签或图像位置

javascript - 从数组创建对象树

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c++ - 数组大小错误

java - 计算具有重复项的数组列表中每个不同数组的出现次数