贴代码:
- (void)compare2{
NSString *theString = @"a👌3👌";
NSLog(@"theString--->%@",theString);
//方法一(错误,emoji不打印)
for (int i = 0; i < theString.length; i++) {
unichar ch = [theString characterAtIndex:i];
NSString *everyString = [NSString stringWithCharacters:&ch length:1];
NSLog(@"everyString--->%@",everyString);
}
//打印:
/*
everyString--->a
everyString--->3
*/
//方法二(错误,emoji打印2次)
NSRange range ;
NSRange stringRange = [theString rangeOfString:theString];// log:location=0, length=6
for (int i = 0; i < theString.length; i++) {
range = [theString rangeOfComposedCharacterSequenceAtIndex:i];
NSString *everyString = [theString substringWithRange:range];
NSLog(@"everyString--->%@",everyString);
}
//打印:
/*
everyString--->a
everyString--->👌
everyString--->👌
everyString--->3
everyString--->👌
everyString--->👌
*/
//方法三(正确,可打印emoji)
for(int i=0; i<theString.length; i+=range.length){
range = [theString rangeOfComposedCharacterSequenceAtIndex:i];
NSString *s = [theString substringWithRange:range];
NSLog(@"s--->%@",s);
}
//打印:
/*
s--->a
s--->👌
s--->3
s--->👌
*/
}
方法二和三区别在于:i++ 和 i+=range.length
emoji表情占两个字符位置