转自 http://blog.csdn.net/zhaozy55555/article/details/7672216
utf-8为可变字长编码,大部分汉字占3个字节。用 NSString::UTF8String函数转化utf-8编码格式为多字节格式,就可以判断出一个字符占用几个字节了。
代码如下:
const char* strTest = "我一123兵";
int s8len = strlen(strTest);
NSLog(@"s8=%d",s8len);//12
NSString* nsstrTest = [[NSString alloc] initWithUTF8String:strTest];
int nsstrLen = nsstrTest.length;
NSLog(@"ns=%d",nsstrLen);//6
NSRange range;
range.length=1;
for (range.location=0; range.location<nsstrTest.length ; range.location++)
{
NSString* temp = [nsstrTest substringWithRange:range];
const char* u8Temp = [temp UTF8String];
if (3==strlen(u8Temp))
{
NSLog(@"this is chinese");
}
else
{
NSLog(@"this is english");
}
}