07-18-2023, 11:30 PM
For Xcode 7.3 and Swift 2.2.
let str = "🐶"
1. If you want the number of visual characters:
str.characters.count
2. If you want the "16-bit code units within the string’s UTF-16 representation":
str.utf16.count
----------
Most of the time, **1** is what you need.
When would you need **2**? I've found a use case for **2**:
let regex = try! NSRegularExpression(pattern:"🐶",
options: NSRegularExpressionOptions.UseUnixLineSeparators)
let str = "🐶🐶🐶🐶🐶🐶"
let result = regex.stringByReplacingMatchesInString(str,
options: NSMatchingOptions.WithTransparentBounds,
range: NSMakeRange(0, str.utf16.count), withTemplate: "dog")
print(result) // dogdogdogdogdogdog
If you use **1**, the result is incorrect:
let result = regex.stringByReplacingMatchesInString(str,
options: NSMatchingOptions.WithTransparentBounds,
range: NSMakeRange(0, str.characters.count), withTemplate: "dog")
print(result) // dogdogdog🐶🐶🐶
let str = "🐶"
1. If you want the number of visual characters:
str.characters.count
2. If you want the "16-bit code units within the string’s UTF-16 representation":
str.utf16.count
----------
Most of the time, **1** is what you need.
When would you need **2**? I've found a use case for **2**:
let regex = try! NSRegularExpression(pattern:"🐶",
options: NSRegularExpressionOptions.UseUnixLineSeparators)
let str = "🐶🐶🐶🐶🐶🐶"
let result = regex.stringByReplacingMatchesInString(str,
options: NSMatchingOptions.WithTransparentBounds,
range: NSMakeRange(0, str.utf16.count), withTemplate: "dog")
print(result) // dogdogdogdogdogdog
If you use **1**, the result is incorrect:
let result = regex.stringByReplacingMatchesInString(str,
options: NSMatchingOptions.WithTransparentBounds,
range: NSMakeRange(0, str.characters.count), withTemplate: "dog")
print(result) // dogdogdog🐶🐶🐶