How to add a character at a particular index in st

2019-01-23 00:45发布

I have a string like this in Swift:

var stringts:String = "3022513240"

If I want to change it to string to something like this: "(302)-251-3240", I want to add the partheses at index 0, how do I do it?

In Objective-C, it is done this way:

 NSMutableString *stringts = "3022513240";
 [stringts insertString:@"(" atIndex:0];

How to do it in Swift?

8条回答
祖国的老花朵
2楼-- · 2019-01-23 01:36

Swift 3

Use the native Swift approach:

var welcome = "hello"

welcome.insert("!", at: welcome.endIndex) // prints hello!
welcome.insert("!", at: welcome.startIndex) // prints !hello
welcome.insert("!", at: welcome.index(before: welcome.endIndex)) // prints hell!o
welcome.insert("!", at: welcome.index(after: welcome.startIndex)) // prints h!ello
welcome.insert("!", at: welcome.index(welcome.startIndex, offsetBy: 3)) // prints hel!lo

If you are interested in learning more about Strings and performance, take a look at @Thomas Deniau's answer down below.

查看更多
时光不老,我们不散
3楼-- · 2019-01-23 01:41

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.

查看更多
登录 后发表回答