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"
-