Skip to content

Instantly share code, notes, and snippets.

@congbo
Last active August 8, 2018 03:23
Show Gist options
  • Save congbo/190e9e032328e97e09df to your computer and use it in GitHub Desktop.
Save congbo/190e9e032328e97e09df to your computer and use it in GitHub Desktop.
计算NSString中英文字符串的字符长度,及按字符长度截取
//计算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