来自NSCharacterSet的NSArray

目前,我能够制作如下的字母数组


[[NSArray alloc]initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",nil];

知道可用


[NSCharacterSet uppercaseLetterCharacterSet]

如何制作一个数组呢?


守着星空守着你
浏览 509回答 3
3回答

森栏

以下代码创建一个包含给定字符集的所有字符的数组。它也适用于“基本多语言平面”之外的字符(字符> U + FFFF,例如U + 10400 DESERET CAPITAL LETTER LONG I)。NSCharacterSet *charset = [NSCharacterSet uppercaseLetterCharacterSet];NSMutableArray *array = [NSMutableArray array];for (int plane = 0; plane <= 16; plane++) {&nbsp; &nbsp; if ([charset hasMemberInPlane:plane]) {&nbsp; &nbsp; &nbsp; &nbsp; UTF32Char c;&nbsp; &nbsp; &nbsp; &nbsp; for (c = plane << 16; c < (plane+1) << 16; c++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ([charset longCharacterIsMember:c]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; UTF32Char c1 = OSSwapHostToLittleInt32(c); // To make it byte-order safe&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; NSString *s = [[NSString alloc] initWithBytes:&c1 length:4 encoding:NSUTF32LittleEndianStringEncoding];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [array addObject:s];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}为此,uppercaseLetterCharacterSet给出了1467个元素的数组。但请注意,字符> U + FFFF作为UTF-16代理对存储在中NSString,因此例如U + 10400实际上存储NSString为2个字符“ \ uD801 \ uDC00”。Swift 2代码可以在此问题的其他答案中找到。这是一个Swift 3版本,作为扩展方法编写的:extension CharacterSet {&nbsp; &nbsp; func allCharacters() -> [Character] {&nbsp; &nbsp; &nbsp; &nbsp; var result: [Character] = []&nbsp; &nbsp; &nbsp; &nbsp; for plane: UInt8 in 0...16 where self.hasMember(inPlane: plane) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if let uniChar = UnicodeScalar(unicode), self.contains(uniChar) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.append(Character(uniChar))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return result&nbsp; &nbsp; }}例:let charset = CharacterSet.uppercaseLetterslet chars = charset.allCharacters()print(chars.count) // 1521print(chars) // ["A", "B", "C", ... "](请注意,某些字符可能不会显示在用于显示结果的字体中。)
打开App,查看更多内容
随时随地看视频慕课网APP