Formatting Phone number in Swift

前端 未结 12 1860
天命终不由人
天命终不由人 2020-12-02 09:36

I\'m formatting my textfiled text once the user start typing the phone number into this format type 0 (555) 444 66 77 and it is working fine but once I get the

12条回答
  •  攒了一身酷
    2020-12-02 10:04

    Manipulations with characters in String are not very straightforward. You need following:

    Swift 2.1

    let s = "05554446677"
    let s2 = String(format: "%@ (%@) %@ %@ %@", s.substringToIndex(s.startIndex.advancedBy(1)),
        s.substringWithRange(s.startIndex.advancedBy(1) ... s.startIndex.advancedBy(3)),
        s.substringWithRange(s.startIndex.advancedBy(4) ... s.startIndex.advancedBy(6)),
        s.substringWithRange(s.startIndex.advancedBy(7) ... s.startIndex.advancedBy(8)),
        s.substringWithRange(s.startIndex.advancedBy(9) ... s.startIndex.advancedBy(10))
    )
    

    Swift 2.0

    let s = "05554446677"
    let s2 = String(format: "%@ (%@) %@ %@ %@", s.substringToIndex(advance(s.startIndex, 1)),
        s.substringWithRange(advance(s.startIndex, 1) ... advance(s.startIndex, 3)),
        s.substringWithRange(advance(s.startIndex, 4) ... advance(s.startIndex, 6)),
        s.substringWithRange(advance(s.startIndex, 7) ... advance(s.startIndex, 8)),
        s.substringWithRange(advance(s.startIndex, 9) ... advance(s.startIndex, 10))
    )
    

    Code will print 0 (555) 444 66 77

提交回复
热议问题