Filter non-digits from string

后端 未结 12 1133
日久生厌
日久生厌 2020-12-01 11:36

Using only swift code I cant figure out how to take \"(555) 555-5555\" and return only the numeric values and get \"5555555555\". I need to remove all the parentheses, whit

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 12:34

    Split the string by non-digit characters to an array of digits and the join them back to a string:

    Swift 1:

    let stringArray = origString.componentsSeparatedByCharactersInSet(
        NSCharacterSet.decimalDigitCharacterSet().invertedSet)
    let newString = NSArray(array: stringArray).componentsJoinedByString("")
    

    Swift 2:

    let stringArray = origString.componentsSeparatedByCharactersInSet(
        NSCharacterSet.decimalDigitCharacterSet().invertedSet)
    let newString = stringArray.joinWithSeparator("")
    

    Swift 3 & 4:

    let newString = origString
        .components(separatedBy:CharacterSet.decimalDigits.inverted)
        .joined()
    

提交回复
热议问题