Swift string count() 与 NSString .length 不相等
Swift string count() vs NSString .length not equal
为什么这两行给我不同的结果?
var str = "Hello " // the square is an emoji
count(str) // returns 7
(str as NSString).length // returns 8
原文供参考:
我认为 documentation 说得最好:
The character count returned by the count(_:) function is not always the same as the length property of an NSString that contains the same characters. The length of an NSString is based on the number of 16-bit code units within the string’s UTF-16 representation and not the number of Unicode extended grapheme clusters within the string. To reflect this fact, the length property from NSString is called utf16Count when it is accessed on a Swift String value.
这是因为Swift使用扩展字素簇。 Swift 将笑脸视为一个字符,但 NSString 方法将其视为两个 Unicode 字符,尽管它们是 "combined" 并表示单个符号。
为什么这两行给我不同的结果?
var str = "Hello " // the square is an emoji
count(str) // returns 7
(str as NSString).length // returns 8
原文供参考:
我认为 documentation 说得最好:
The character count returned by the count(_:) function is not always the same as the length property of an NSString that contains the same characters. The length of an NSString is based on the number of 16-bit code units within the string’s UTF-16 representation and not the number of Unicode extended grapheme clusters within the string. To reflect this fact, the length property from NSString is called utf16Count when it is accessed on a Swift String value.
这是因为Swift使用扩展字素簇。 Swift 将笑脸视为一个字符,但 NSString 方法将其视为两个 Unicode 字符,尽管它们是 "combined" 并表示单个符号。