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

后端 未结 9 1356
自闭症患者
自闭症患者 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题