我在Swift中有这样的字符串:
var stringts:String = "3022513240"
如果我想将它更改为字符串,如下所示:"(302)-251-3240"
,我想在索引0处添加括号,我该怎么做?
在Objective-C中,它是这样完成的:
NSMutableString *stringts = "3022513240"; [stringts insertString:@"(" atIndex:0];
怎么在Swift中做到这一点?
也许Swift 4的这个扩展会有所帮助:
extension String { mutating func insert(string:String,ind:Int) { self.insert(contentsOf: string, at:self.index(self.startIndex, offsetBy: ind) ) } }
var phone ="+ 9945555555"
var indx = phone.index(phone.startIndex,offsetBy:4)
phone.insert(" - ",at:indx)
index = phone.index(phone.startIndex,offsetBy:7)
phone.insert(" - ",at:indx)
// + 994-55-55555
如果你宣布它NSMutableString
是可能的,你可以这样做:
let str: NSMutableString = "3022513240)" str.insert("(", at: 0) print(str)
输出是:
(3022513240)
编辑:
如果你想在开始时添加:
var str = "3022513240)" str.insert("(", at: str.startIndex)
如果要在最后一个索引处添加字符:
str.insert("(", at: str.endIndex)
如果你想添加特定的索引:
str.insert("(", at: str.index(str.startIndex, offsetBy: 2))
使用本机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的答案.
var myString = "hell" let index = 4 let character = "o" as Character myString.insert( character, at: myString.index(myString.startIndex, offsetBy: index) ) print(myString) // "hello"
小心:确保index
大于或等于字符串的大小,否则你会崩溃.
将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 }