objective c - NSArray from NSCharacterset -
currently able make array of alphabets 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];
knowing available over
[nscharacterset uppercaselettercharacterset]
is there anyway can make array out of it?
the following code creates array containing characters of given character set. works characters outside of "basic multilingual plane" (characters > u+ffff, e.g. u+10400 deseret capital letter long i).
nscharacterset *charset = [nscharacterset uppercaselettercharacterset]; nsmutablearray *array = [nsmutablearray array]; (int plane = 0; plane <= 16; plane++) { if ([charset hasmemberinplane:plane]) { utf32char c; (c = plane << 16; c < (plane+1) << 16; c++) { if ([charset longcharacterismember:c]) { utf32char c1 = osswaphosttolittleint32(c); // make byte-order safe nsstring *s = [[nsstring alloc] initwithbytes:&c1 length:4 encoding:nsutf32littleendianstringencoding]; [array addobject:s]; } } } }
for uppercaselettercharacterset
gives array of 1467 elements. note characters > u+ffff stored utf-16 surrogate pair in nsstring
, example u+10400 stored in nsstring
2 characters "\ud801\udc00".
swift 2 code can found in other answers question. here swift 3 version, written extension method:
extension characterset { func allcharacters() -> [character] { var result: [character] = [] plane: uint8 in 0...16 self.hasmember(inplane: plane) { unicode in uint32(plane) << 16 ..< uint32(plane + 1) << 16 { if let unichar = unicodescalar(unicode), self.contains(unichar) { result.append(character(unichar)) } } } return result } }
example:
let charset = characterset.uppercaseletters let chars = charset.allcharacters() print(chars.count) // 1521 print(chars) // ["a", "b", "c", ... "]
(note characters may not present in font used display result.)
Comments
Post a Comment