我在Swift中有一个像这样的字符串:
var stringts:String = "3022513240"
如果我想将其更改为类似于以下内容的字符串:"(302)-251-3240"
,我想在索引0处添加括号,我该怎么做?
在Objective-C中,是通过以下方式完成的:
NSMutableString *stringts = "3022513240";
[stringts insertString:@"(" atIndex:0];
在Swift中如何做?
如果您声明为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))
迅捷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的答案。
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
值大于或等于字符串的大小,否则将导致崩溃。
也许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(“-”,位于:indx)
索引= phone.index(phone.startIndex,offsetBy:7)
phone.insert(“-”,位于:indx)
// + 994-55-55555
将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
}
您不能这样做,因为在Swift字符串索引(String.Index)中是根据Unicode字形簇定义的,因此它可以很好地处理所有Unicode内容。因此,您不能直接从索引构造String.Index。您可以advance(theString.startIndex, 3)
用来查看组成字符串的群集并计算与第三个群集相对应的索引,但是请注意,这是一个O(N)操作。
在您的情况下,使用字符串替换操作可能会更容易。
查看此博客文章以了解更多详细信息。
您不能在Swift 2.0以下使用它,因为在Swift 2.0中String
已不再使用collection
。但是在斯威夫特3/4的不再是必要的,现在String
是Collection
试。使用原生的做法String
,Collection
。
var stringts:String = "3022513240"
let indexItem = stringts.index(stringts.endIndex, offsetBy: 0)
stringts.insert("0", at: indexItem)
print(stringts) // 30225132400
Swift 4.2版本的Dilmurat的答案(已修复代码)
extension String {
mutating func insert(string:String,ind:Int) {
self.insert(contentsOf: string, at:self.index(self.startIndex, offsetBy: ind) )
}
}
请注意,如果您希望索引必须与要插入的字符串(自身)而不是所提供的字符串相反。
评论已关闭!