如何在Swift中以string的特定索引添加一个字符

我在Swift中有这样一个string:

var stringts:String = "3022513240" 

如果我想把它改成这样的string: "(302)-251-3240" ,我想在索引0处添加partheses,我该怎么做?

在Objective-C中,它是这样做的:

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

如何在Swift中做到这一点?

如果你声明它为NSMutableString那么这是可能的,你可以这样做:

 var str : NSMutableString = "3022513240)" str.insertString("(", atIndex: 0) print(str) 

输出是:

 (3022513240) 

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 

如果您有兴趣了解更多关于string和性能的信息,请看下面的 @Thomas Deniau的回答。

简短的回答:

 let index = 5 let character = "c" as Character myString.insert(character, atIndex: advance(myString.startIndex, index)) 

小心:确保index大于string的大小,否则会发生崩溃。

漫长的回答:

不同的字符可能需要不同的内存量来存储,所以为了确定哪个字符位于某个特定的位置,必须从该string的开头或结尾迭代每个Unicode标量。 由于这个原因, Swiftstring不能被整数值索引

从文档 (我强调)。

所以,如果你认为你的string中的所有字素占用相同的内存量,上面的简短答案将起作用。

此外,正如@ThomasDeniau所说,复杂性(从Swift v1.2开始) O(N) ,但对于相对较短的string,性能不会受到明显的影响。

你不能这样做,因为在Swift中,string索引(String.Index)是用Unicode字形串来定义的,所以它很好地处理了所有Unicode的东西。 所以你不能直接从索引构造一个String.Index。 您可以使用advance(theString.startIndex, 3)查看组成string的集群并计算与第三个集群相对应的索引,但请注意,这是O(N)操作。

在你的情况下,使用stringreplace操作可能更容易。

看看这个博客文章了解更多细节。

要将10位电话号码显示为美国数字格式(###)### – #### SWIFT 3

 func arrangeUSFormat(strPhone : String)-> String { var strUpdated = strPhone if strPhone.characters.count == 10 { strUpdated.insert("(", at: strUpdated.startIndex) strUpdated.insert(")", at: strUpdated.index(strUpdated.startIndex, offsetBy: 4)) strUpdated.insert(" ", at: strUpdated.index(strUpdated.startIndex, offsetBy: 5)) strUpdated.insert("-", at: strUpdated.index(strUpdated.startIndex, offsetBy: 9)) } return strUpdated }