gpt4 book ai didi

swift - 将字符添加到字符串中的特定索引 - swift 3

转载 作者:可可西里 更新时间:2023-10-31 23:57:49 26 4
gpt4 key购买 nike

我正在尝试在字符串的特定索引中插入特定字符

var text = "1234567890"

我希望该变量添加电话号码的国家/地区代码:

text = text.replacingCharacters(in: text.startIndex..<text.index(after: text.startIndex), with: "+593\\U00a0")

然后我必须将该字符串格式化为这样的格式:“+593 23-456-7890”,因此我必须将“-”插入索引 8 和 11,但我只找到了 swift 2.0 的答案。字符串有一个名为 insert 的方法,但该方法已不存在。我试过这个:

text = text.insert("-", at: text.index(text.startIndex, offsetBy: +8))

但我有以下错误“无法将类型 '()' 的值分配给类型 'String'

最佳答案

Insert 对实际字符串本身进行操作。因此,没有必要重新分配给它。您可以只使用以下内容:

text.insert("-", at: text.index(text.startIndex, offsetBy: +8))

有关插入字符串的更多信息,请参阅 Swift documentation from Apple .

关于swift - 将字符添加到字符串中的特定索引 - swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40352871/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com