我在 Swift 中有这样一个字符串:
var stringts:String = "3022513240"
如果我想将其更改为类似这样的字符串:"(302)-251-3240"
,我想在索引 0 处添加括号,我该怎么做?
在 Objective-C 中,它是这样完成的:
NSMutableString *stringts = "3022513240";
[stringts insertString:@"(" atIndex:0];
如何在 Swift 中实现?
最佳答案
swift 3
使用原生的 Swift 方法:
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
如果您有兴趣了解有关字符串和性能的更多信息,请查看 @Thomas Deniau's回答down below .
关于ios - 如何在 Swift 中的字符串中的特定索引处添加字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27103454/