来自NSCharacterSet的NSArray [英] NSArray from NSCharacterSet
问题描述
目前,我能够像下面那样制作字母数组
Currently I am able to make array of Alphabets like below
[[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]
如何用它制作一个数组?
How to make an array out of it?
推荐答案
以下代码创建一个包含给定字符集的所有字符的数组.它也适用于基本多语言平面"之外的字符(字符> U + FFFF,例如U + 10400 DESERET CAPITAL LETTER LONG I).
The following code creates an array containing all characters of a given character set. It works also for characters outside of the "basic multilingual plane" (characters > U+FFFF, e.g. U+10400 DESERET CAPITAL LETTER LONG I).
NSCharacterSet *charset = [NSCharacterSet uppercaseLetterCharacterSet];
NSMutableArray *array = [NSMutableArray array];
for (int plane = 0; plane <= 16; plane++) {
if ([charset hasMemberInPlane:plane]) {
UTF32Char c;
for (c = plane << 16; c < (plane+1) << 16; c++) {
if ([charset longCharacterIsMember:c]) {
UTF32Char c1 = OSSwapHostToLittleInt32(c); // To make it byte-order safe
NSString *s = [[NSString alloc] initWithBytes:&c1 length:4 encoding:NSUTF32LittleEndianStringEncoding];
[array addObject:s];
}
}
}
}
对于uppercaseLetterCharacterSet
,这给出了1467个元素的数组.但是请注意,字符> U + FFFF作为UTF-16代理对存储在NSString
中,因此,例如,U + 10400实际上存储在NSString
中,是2个字符"\ uD801 \ uDC00".
For the uppercaseLetterCharacterSet
this gives an array of 1467 elements. But note that characters > U+FFFF are stored as UTF-16 surrogate pair in NSString
, so for example U+10400 actually is stored in NSString
as 2 characters "\uD801\uDC00".
Swift 2 代码. 这是 Swift 3 版本,是作为扩展方法编写的:
Swift 2 code can be found in other answers to this question. Here is a Swift 3 version, written as an extension method:
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 charset = CharacterSet.uppercaseLetters
let chars = charset.allCharacters()
print(chars.count) // 1521
print(chars) // ["A", "B", "C", ... "]
(请注意,某些字符可能不包含在用于 显示结果.)
(Note that some characters may not be present in the font used to display the result.)
这篇关于来自NSCharacterSet的NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!