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

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

提交回复
热议问题