如何在Swift的字符串中添加一个字符?

时间:2021-11-03 19:35:13

I have a string like this in Swift:

我有一根像这样的线绳:

var stringts:String = "3022513240"

If I want to change it to string to something like this: "(302)-251-3240", I want to add the partheses at index 0, how do I do it?

如果我想把它变成这样的字符串:“(302)-251-3240”,我想要在索引0处加上这些式子,我该怎么做?

In Objective-C, it is done this way:

Objective-C中是这样的

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

How to do it in Swift?

如何用Swift操作?

8 个解决方案

#1


12  

If you are declaring it as NSMutableString then it is possible and you can do it this way:

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

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

The output is :

的输出是:

(3022513240)

#2


56  

Swift 3

Use the native Swift approach:

使用本地的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

If you are interested in learning more about Strings and performance, take a look at @Thomas Deniau's answer down below.

如果你想了解更多关于字符串和性能的信息,请看下面@Thomas Deniau的回答。

#3


5  

The short answer:

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

Careful: make sure that index is bigger than the size of the string, otherwise you'll get a crash.

注意:确保索引大于字符串的大小,否则会导致崩溃。

The long answer:

Different characters can require different amounts of memory to store, so in order to determine which Character is at a particular position, you must iterate over each Unicode scalar from the start or end of that String. For this reason, Swift strings cannot be indexed by integer values.

不同的字符可能需要不同数量的内存来存储,因此为了确定哪个字符位于某个特定位置,必须从该字符串的开头或结尾遍历每个Unicode标量。因此,不能用整数值来索引Swift字符串。

From the documentation (my emphasis).

来自文档(我的重点)。

So the above short answer will work if you assume that all the graphemes in your string take up an equal amount of memory.

因此,如果您假设字符串中的所有图形都占用相同的内存,那么上面的简短回答就可以了。

Additionally, as @ThomasDeniau mentioned, complexity is (as of Swift v1.2) O(N), but for relatively short strings performance won't be noticeably affected.

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

#4


4  

You can't, because in Swift string indices (String.Index) is defined in terms of Unicode grapheme clusters, so that it handles all the Unicode stuff nicely. So you cannot construct a String.Index from an index directly. You can use advance(theString.startIndex, 3) to look at the clusters making up the string and compute the index corresponding to the third cluster, but caution, this is an O(N) operation.

您不能这样做,因为在Swift字符串索引(string . index)中是根据Unicode grapheme集群定义的,因此它可以很好地处理所有的Unicode内容。所以你不能构造一个字符串。索引直接来自索引。您可以使用(theString前进。查看组成字符串的集群并计算与第三个集群对应的索引,但是要注意,这是一个O(N)操作。

In your case, it's probably easier to use a string replacement operation.

在您的示例中,使用字符串替换操作可能更容易。

Check out this blog post for more details.

查看这篇博文了解更多细节。

#5


4  

var phone= "+9945555555"

电话var = " + 9945555555”

var indx = phone.index(phone.startIndex,offsetBy: 4)

var indx = phone.index(电话。startIndex offsetBy:4)

phone.insert("-", at: indx)

电话。插入(“-”:indx)

index = phone.index(phone.startIndex, offsetBy: 7)

指数= phone.index(电话。startIndex offsetBy:7)

phone.insert("-", at: indx)

电话。插入(“-”:indx)

//+994-55-55555

/ / + 994-55-55555

#6


2  

To Display 10 digit phone number into USA Number format (###) ###-#### SWIFT 3

显示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
}

#7


0  

Maybe this extension for Swift 4 will help:

Swift 4的扩展可能会有所帮助:

extension String {
    mutating func insert(string:String,ind:Int) {
        self.insert(contentsOf: string, at:string.index(string.startIndex, offsetBy: ind) )
    }
}

#8


0  

You can't use in below Swift 2.0 because String stopped being a collection in Swift 2.0. but in Swift 3 / 4 is no longer necessary now that String is a Collection again. Use native approach of String,Collection.

在Swift 2.0下面不能使用,因为在Swift 2.0中字符串不再是集合。但是在Swift 3 / 4中不再需要字符串,因为该字符串再次是一个集合。使用字符串的本地方法,集合。

var stringts:String = "3022513240"
let indexItem = stringts.index(stringts.endIndex, offsetBy: 0)
stringts.insert("0", at: indexItem)
print(stringts) // 30225132400

#1


12  

If you are declaring it as NSMutableString then it is possible and you can do it this way:

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

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

The output is :

的输出是:

(3022513240)

#2


56  

Swift 3

Use the native Swift approach:

使用本地的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

If you are interested in learning more about Strings and performance, take a look at @Thomas Deniau's answer down below.

如果你想了解更多关于字符串和性能的信息,请看下面@Thomas Deniau的回答。

#3


5  

The short answer:

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

Careful: make sure that index is bigger than the size of the string, otherwise you'll get a crash.

注意:确保索引大于字符串的大小,否则会导致崩溃。

The long answer:

Different characters can require different amounts of memory to store, so in order to determine which Character is at a particular position, you must iterate over each Unicode scalar from the start or end of that String. For this reason, Swift strings cannot be indexed by integer values.

不同的字符可能需要不同数量的内存来存储,因此为了确定哪个字符位于某个特定位置,必须从该字符串的开头或结尾遍历每个Unicode标量。因此,不能用整数值来索引Swift字符串。

From the documentation (my emphasis).

来自文档(我的重点)。

So the above short answer will work if you assume that all the graphemes in your string take up an equal amount of memory.

因此,如果您假设字符串中的所有图形都占用相同的内存,那么上面的简短回答就可以了。

Additionally, as @ThomasDeniau mentioned, complexity is (as of Swift v1.2) O(N), but for relatively short strings performance won't be noticeably affected.

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

#4


4  

You can't, because in Swift string indices (String.Index) is defined in terms of Unicode grapheme clusters, so that it handles all the Unicode stuff nicely. So you cannot construct a String.Index from an index directly. You can use advance(theString.startIndex, 3) to look at the clusters making up the string and compute the index corresponding to the third cluster, but caution, this is an O(N) operation.

您不能这样做,因为在Swift字符串索引(string . index)中是根据Unicode grapheme集群定义的,因此它可以很好地处理所有的Unicode内容。所以你不能构造一个字符串。索引直接来自索引。您可以使用(theString前进。查看组成字符串的集群并计算与第三个集群对应的索引,但是要注意,这是一个O(N)操作。

In your case, it's probably easier to use a string replacement operation.

在您的示例中,使用字符串替换操作可能更容易。

Check out this blog post for more details.

查看这篇博文了解更多细节。

#5


4  

var phone= "+9945555555"

电话var = " + 9945555555”

var indx = phone.index(phone.startIndex,offsetBy: 4)

var indx = phone.index(电话。startIndex offsetBy:4)

phone.insert("-", at: indx)

电话。插入(“-”:indx)

index = phone.index(phone.startIndex, offsetBy: 7)

指数= phone.index(电话。startIndex offsetBy:7)

phone.insert("-", at: indx)

电话。插入(“-”:indx)

//+994-55-55555

/ / + 994-55-55555

#6


2  

To Display 10 digit phone number into USA Number format (###) ###-#### SWIFT 3

显示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
}

#7


0  

Maybe this extension for Swift 4 will help:

Swift 4的扩展可能会有所帮助:

extension String {
    mutating func insert(string:String,ind:Int) {
        self.insert(contentsOf: string, at:string.index(string.startIndex, offsetBy: ind) )
    }
}

#8


0  

You can't use in below Swift 2.0 because String stopped being a collection in Swift 2.0. but in Swift 3 / 4 is no longer necessary now that String is a Collection again. Use native approach of String,Collection.

在Swift 2.0下面不能使用,因为在Swift 2.0中字符串不再是集合。但是在Swift 3 / 4中不再需要字符串,因为该字符串再次是一个集合。使用字符串的本地方法,集合。

var stringts:String = "3022513240"
let indexItem = stringts.index(stringts.endIndex, offsetBy: 0)
stringts.insert("0", at: indexItem)
print(stringts) // 30225132400