Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make unicode characters from integers?

I want to make an array of Unicode characters, but I don't know how to convert integers into a Unicode representation. Here's the code I have so far

NSMutableArray *uniArray = [[NSMutableArray alloc] initWithCapacity:0];
int i;

for (i = 32; i < 300; i++) {
    NSString *uniString = [NSString stringWithFormat:@"\u%04X", i];
    [uniArray addObject:uniString];
}

Which gives me an error "incomplete universal character name \u"

Is there a better way to build an array of Unicode symbols? Thanks.

like image 282
nevan king Avatar asked Jul 22 '09 06:07

nevan king


3 Answers

You should use %C to insert a unicode character:

NSMutableArray *uniArray = [[NSMutableArray alloc] initWithCapacity:0];
int i;

for (i = 32; i < 300; i++) {
   NSString *uniString = [NSString stringWithFormat:@"%C", i];
   [uniArray addObject:uniString];
}

Another (better?) way is using stringWithCharacters:

NSMutableArray *uniArray = [[NSMutableArray alloc] initWithCapacity:0];
int i;

for (i = 32; i < 300; i++) {
   NSString *uniString = [NSString stringWithCharacters:(unichar *)&i length:1];
   [uniArray addObject:uniString];
}
like image 67
Philippe Leybaert Avatar answered Sep 26 '22 19:09

Philippe Leybaert


The reason for the error is that \u must be followed by four hexadecimal digits at compile time. You've followed it with “%04x”, apparently with the intent of inserting those four hexadecimal digits at run time, which is too late—the compiler has long ago finished its work by then, and the compiler is what is giving you this error.

like image 29
Peter Hosey Avatar answered Sep 24 '22 19:09

Peter Hosey


If you want a single UTF-16 character, [NSString stringWithCharacters:&character length:1]. If it’s UTF-32, you’d have to convert to surrogate pairs, or use -initWithData:encoding:, or try what Philippe said (I’m not sure offhand whether that handle’s UTF-32 properly, but it should).

like image 40
Jens Ayton Avatar answered Sep 23 '22 19:09

Jens Ayton