如何计算字符串的长度?例如,我有一个定义如下的变量:

var test1: String = "Scott"

然而,我似乎找不到字符串的长度方法。


当前回答

在swift4中,我一直使用string.count,直到今天我发现

string.endIndex.encodedOffset

是更好的替代方法,因为它更快-对于50000个字符,字符串大约比.count快6倍。.count取决于字符串长度,但.endIndex.encodedOffset不一样。

但有一个“不”。它对带有表情符号的字符串不好,它会给出错误的结果,所以只有count是正确的。

其他回答

var str = "Hello, playground"
var newString = str as NSString    

countElements(str)

这将统计正则Swift字符串中的字符

countElements((newString as String))    

这将统计NSString中的字符

您可以使用str.utf8.count和str.utf16.count,我认为这是最好的解决方案

在Swift 4.2和Xcode 10.1中

在Swift中,字符串可以被视为单个字符的数组。所以字符串中的每个字符就像数组中的一个元素。要获取字符串的长度,请使用StringName.count属性。

在Swift中

yourStringName.character.count属性已弃用。所以直接使用strLength.count属性。

let strLength = "This is my string"
print(strLength.count)
//print(strLength.characters.count) //Error: 'characters' is deprecated: Please use String or Substring directly

如果目标C

NSString *myString = @"Hello World";
NSLog(@"%lu", [myString length]); // 11

我的两美分换雨燕3/4

如果需要有条件地编译

    #if swift(>=4.0)
            let len = text.count
        #else
            let len = text.characters.count
        #endif

你可以这样试试

var test1: String = "Scott"
var length =  test1.bridgeToObjectiveC().length