Mar*_*n R 18
Swift 4更新(Xcode 9)
从Swift 4开始,"表情符号序列"被视为单个字形簇(根据Unicode 9标准):
let s = "ab?????"
print(s.count) // 4
Run Code Online (Sandbox Code Playgroud)
所以不再需要其他解决方法了.
(Swift 3及更早版本的旧答案:)
一个可能的选择是枚举和计算字符串中的"组合字符序列":
let s = "ab?????"
var count = 0
s.enumerateSubstringsInRange(s.startIndex..<s.endIndex,
options: .ByComposedCharacterSequences) {
(char, _, _, _) in
if let char = char {
count += 1
}
}
print(count) // 4
Run Code Online (Sandbox Code Playgroud)
另一种选择是在给定索引处找到组合字符序列的范围:
let s = "?????"
if s.rangeOfComposedCharacterSequenceAtIndex(s.startIndex) == s.characters.indices {
print("This is a single composed character")
}
Run Code Online (Sandbox Code Playgroud)
作为String
扩展方法:
// Swift 2.2:
extension String {
var composedCharacterCount: Int {
var count = 0
enumerateSubstringsInRange(characters.indices, options: .ByComposedCharacterSequences) {
(_, _, _, _) in count += 1
}
return count
}
var isSingleComposedCharacter: Bool {
return rangeOfComposedCharacterSequenceAtIndex(startIndex) == characters.indices
}
}
// Swift 3:
extension String {
var composedCharacterCount: Int {
var count = 0
enumerateSubstrings(in: startIndex..<endIndex, options: .byComposedCharacterSequences) {
(_, _, _, _) in count += 1
}
return count
}
var isSingleComposedCharacter: Bool {
return rangeOfComposedCharacterSequence(at: startIndex) == startIndex..<endIndex
}
}
Run Code Online (Sandbox Code Playgroud)
例子:
"".composedCharacterCount // 1
"".characters.count // 2
"?????".composedCharacterCount // 1
"?????".characters.count // 4
"".composedCharacterCount // 2
"".characters.count // 1
Run Code Online (Sandbox Code Playgroud)
如您所见,Swift字符(扩展字形簇)的数量可以多于或少于组合字符序列的数量.
归档时间: |
|
查看次数: |
1418 次 |
最近记录: |