Swift 获取字符串长度
- 字符串的长度获取,可以从以下几种情况理解
- 字符长度(语义理解的长度)
- 不同字符编码的长度
- 字符串unicode长度
- 字符串utf16长度
- 字符串utf32长度(和unicode相等)
- 字符串UTF-8长度
-
语义字符长度
let cafe = "Cafe\u{301} du " print(cafe) // Prints "Café du " print(cafe.count) // Prints "9" print(Array(cafe)) // Prints "["C", "a", "f", "é", " ", "d", "u", " ", ""]"
-
不同字符编码的长度
- unicode字符长度print(cafe.utf16.count) // Prints "11" print(Array(cafe.utf16)) // Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 55356, 57101]" - utf16字符长度 let nscafe = cafe as NSString print(nscafe.length) // Prints "11" print(nscafe.character(at: 3)) // Prints "101" - UTF-8字符长度 print(cafe.utf8.count) // Prints "14" print(Array(cafe.utf8)) // Prints "[67, 97, 102, 101, 204, 129, 32, 100, 117, 32, 240, 159, 140, 141]"
-
-
How to measuring the Length of a String
-
sample1:
let capitalA = "A" print(capitalA.count) // Prints "1" print(capitalA.unicodeScalars.count) // Prints "1" print(capitalA.utf16.count) // Prints "1" print(capitalA.utf8.count) // Prints "1"
-
sample2:
let flag = "" print(flag.count) // Prints "1" print(flag.unicodeScalars.count) // Prints "2" print(flag.utf16.count) // Prints "4" print(flag.utf8.count) // Prints "8"
-