How to get the "real length" of a NSString
Say I got a st开发者_高级运维ring like:
NSString *str = @"abc一二三";
which contains both English and Chinese, if I use the [str length] I got the result 6. The result I want is 1+1+1+2+2+2 = 9, one Chinese character equals 2 English letter.
Hope somebody could help me, thanks^_^
Well, it would be tedious, but you could create your own String Length method. A method with a switch statement that examines the characters individually and assigns integer values accordingly, then returns the total. For example:
- (NSInteger)specialStringLength:(NSString *)theString {
int realLength=0;
for(int x=0;x<[theString length];x++)
{
char thisOne = [theString characterAtIndex:x];
switch(thisOne) {
case 'a':
realLength++;
break;
// and so on...
case '三':
realLength+=2;
break;
// and so on...
}
}
return realLength;
}
Maybe you can convert NSString to NSData, and use the length of NSData.
精彩评论