如何解析每个汉字?

Lis*_*isa 2 objective-c

给出一个由X个汉字组成的句子.我想用Objective-C或C++解析每个字符.

我试过了:

NSString * nsText = [NSString stringWithFormat:@"???"];
for (int i = 0; i < [nsText length]; i++) 
{
  char current = [nsText characterAtIndex:i];
  printf("%i: %c\n", i, current);
}
Run Code Online (Sandbox Code Playgroud)

但我没有得到正确的字符,我得到索引0 =',索引1 =}等.长度正确返回,等于3.我需要UTF8编码将其显示到UI.

任何提示都会有所帮助.谢谢

Jos*_*ell 5

三件事错了.首先,characterAtIndex:返回a unichar,它大于char您指定的值.你在那里失去了信息.其次,%c是打印ASCII值(8位)的格式说明符.你想要%C(大写'C')打印一个16位unichar.最后,printf()似乎不接受%C,所以你需要使用NSLog().改写后,我们有:

NSString * nsText = [NSString stringWithFormat:@"???"];
for (int i = 0; i < [nsText length]; i++) 
{
    unichar current = [nsText characterAtIndex:i];
    NSLog(@"%i: %C\n", i, current);
}
Run Code Online (Sandbox Code Playgroud)