gpt4 book ai didi

swift - 奇怪的 String.unicodeScalars 和 CharacterSet 行为

转载 作者:搜寻专家 更新时间:2023-10-31 08:19:51 24 4
gpt4 key购买 nike

我正在尝试使用 Swift 3 CharacterSetString 中过滤出字符,但我很早就陷入困境。 CharacterSet 有一个名为 contains

的方法

func contains(_ member: UnicodeScalar) -> Bool
Test for membership of a particular UnicodeScalar in the CharacterSet.

但是测试它不会产生预期的行为。

let characterSet = CharacterSet.capitalizedLetters

let capitalAString = "A"

if let capitalA = capitalAString.unicodeScalars.first {
print("Capital A is \(characterSet.contains(capitalA) ? "" : "not ")in the group of capital letters")
} else {
print("Couldn't get the first element of capitalAString's unicode scalars")
}

我得到 Capital A is not in the group of capital letters 但我期望相反。

非常感谢。

最佳答案

CharacterSet.capitalizedLetters返回一个字符集,其中包含 Unicode 通用类别 Lt 中的字符,又名“Letter, titlecase”。那是“包含大写字母后跟小写字母的连字(例如 Dž、Lj、Nj 和 Dz)”(比较 Wikipedia: Unicode character propertyUnicode® Standard Annex #44 – Table 12. General_Category Values ).

您可以在此处找到列表:Unicode Characters in the 'Letter, Titlecase' Category .

您还可以使用来自 NSArray from NSCharacterset转储字符的内容设置:

extension CharacterSet {
func allCharacters() -> [Character] {
var result: [Character] = []
for plane: UInt8 in 0...16 where self.hasMember(inPlane: plane) {
for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
if let uniChar = UnicodeScalar(unicode), self.contains(uniChar) {
result.append(Character(uniChar))
}
}
}
return result
}
}

let characterSet = CharacterSet.capitalizedLetters
print(characterSet.allCharacters())

// ["Dž", "Lj", "Nj", "Dz", "ᾈ", "ᾉ", "ᾊ", "ᾋ", "ᾌ", "ᾍ", "ᾎ", "ᾏ", "ᾘ", "ᾙ", "ᾚ", "ᾛ", "ᾜ", "ᾝ", "ᾞ", "ᾟ", "ᾨ", "ᾩ", "ᾪ", "ᾫ", "ᾬ", "ᾭ", "ᾮ", "ᾯ", "ᾼ", "ῌ", "ῼ"]

您可能想要的是 CharacterSet.uppercaseLetters哪个

Returns a character set containing the characters in Unicode General Category Lu and Lt.

关于swift - 奇怪的 String.unicodeScalars 和 CharacterSet 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42252492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com