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

后端 未结 9 1352
自闭症患者
自闭症患者 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:08

    If you are declaring it as NSMutableString then it is possible and you can do it this way:

    let str: NSMutableString = "3022513240)"
    str.insert("(", at: 0)
    print(str)
    

    The output is :

    (3022513240)
    

    EDIT:

    If you want to add at starting:

    var str = "3022513240)"
    str.insert("(", at: str.startIndex)
    

    If you want to add character at last index:

    str.insert("(", at: str.endIndex)
    

    And if you want to add at specific index:

    str.insert("(", at: str.index(str.startIndex, offsetBy: 2))
    

提交回复
热议问题