ios - 如何在 Swift 中的字符串中的特定索引处添加字符

标签 ios string swift insert

我在 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/

相关文章:

java - 比较连接字符串和普通字符串

IOS Swift 关闭标签栏 Controller 并启动一个新的

swift - 货币格式不起作用

ios - 如何在swift项目中集成PayUMoney iOS SDK

ios - 为什么我的 UILabel 没有截断?

objective-c - 从服务器获取数据时的进度条

objective-c - iOS 6 游戏中心

c - 动态内存分配的字符指针分析

C++ : Pick portions/data from a string having fixed format

ios - 如何处理 CoreData 中的非标准 unicode 字符?