How to add a character at a particular index in string in Swift

后端 未结 9 1336
自闭症患者
自闭症患者 2020-12-14 05:30

I have a string like this in Swift:

var stringts:String = \"3022513240\"

If I want to change it to string to something like this: \"(

相关标签:
9条回答
  • 2020-12-14 06:23

    To Display 10 digit phone number into USA Number format (###) ###-#### SWIFT 3

    func arrangeUSFormat(strPhone : String)-> String {
        var strUpdated = strPhone
        if strPhone.characters.count == 10 {
            strUpdated.insert("(", at: strUpdated.startIndex)
            strUpdated.insert(")", at: strUpdated.index(strUpdated.startIndex, offsetBy: 4))
            strUpdated.insert(" ", at: strUpdated.index(strUpdated.startIndex, offsetBy: 5))
            strUpdated.insert("-", at: strUpdated.index(strUpdated.startIndex, offsetBy: 9))
        }
        return strUpdated
    }
    
    0 讨论(0)
  • 2020-12-14 06:25

    You can't, because in Swift string indices (String.Index) is defined in terms of Unicode grapheme clusters, so that it handles all the Unicode stuff nicely. So you cannot construct a String.Index from an index directly. You can use advance(theString.startIndex, 3) to look at the clusters making up the string and compute the index corresponding to the third cluster, but caution, this is an O(N) operation.

    In your case, it's probably easier to use a string replacement operation.

    Check out this blog post for more details.

    0 讨论(0)
  • 2020-12-14 06:26
    var myString = "hell"
    let index = 4
    let character = "o" as Character
    
    myString.insert(
        character, at:
        myString.index(myString.startIndex, offsetBy: index)
    )
    
    print(myString) // "hello"
    

    Careful: make sure that index is bigger than or equal to the size of the string, otherwise you'll get a crash.

    0 讨论(0)
提交回复
热议问题