当前位置 : 主页 > 手机开发 > 其它 >

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

来源:互联网 收集:自由互联 发布时间:2021-06-11
我正在尝试使用 Swift 3 CharacterSet来过滤字符串中的字符,但是我很早就陷入了困境. CharacterSet有一个名为contains的方法 func contains(_ member: UnicodeScalar) - Bool Test for membership of a particular Unico
我正在尝试使用 Swift 3 CharacterSet来过滤字符串中的字符,但是我很早就陷入了困境. 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")
}

我得到资本A不在大写字母组中,但我期望相反.

非常感谢.

CharacterSet.capitalizedLetters
返回一个字符集,其中包含Unicode General Category Lt aka“Letter,titlecase”中的字符.那是
“包含大写字母后跟小写字母的连字符(例如,Dž,Lj,Nj和Dz)”(比较 Wikipedia: Unicode character property或
Unicode® 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.

网友评论