Last active
August 8, 2018 03:23
-
-
Save congbo/190e9e032328e97e09df to your computer and use it in GitHub Desktop.
计算NSString中英文字符串的字符长度,及按字符长度截取
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//计算NSString中英文字符串的字符长度。ios 中一个汉字算2字符数 | |
- (int)charNumber:(NSString*)strtemp | |
{ | |
int strlength = 0; | |
char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding]; | |
for (int i = 0; i < [strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding]; i++) { | |
if (*p) { | |
p++; | |
strlength++; | |
} else { | |
p++; | |
} | |
} | |
return strlength; | |
} | |
// 按字节截取字符串 | |
if ([self charNumber:coopBoxName] > 12) { | |
NSString* tmp; | |
for (int i = coopBoxName.length; i > 0; i--) { | |
tmp = [coopBoxName substringToIndex:i]; | |
if ([self charNumber:tmp] <= 9) { | |
coopBoxName = [tmp stringByAppendingString:@"..."]; | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment