Filter non-digits from string

后端 未结 12 1131
日久生厌
日久生厌 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:16

    Try this:

    let string = "(555) 555-5555"
    let digitString = string.filter { ("0"..."9").contains($0) }
    print(digitString) // 5555555555
    

    Putting in extension:

    extension String
    {
        var digitString: String { filter { ("0"..."9").contains($0) } }
    }
    
    print("(555) 555-5555".digitString) // 5555555555
    

提交回复
热议问题