//首先先新建一个NSString的Category类
//获取NSString对应的字符长度
- (int)chineseLength
{
int asciiCount = 0;
int nonAsciiCount = 0;
for (NSUInteger i = 0; i < self.length; i++) {
unichar c = [self characterAtIndex:i];
if (isascii(c)) {
asciiCount++;
} else {
nonAsciiCount++;
}
}
int count = (asciiCount + 1) / 2 + nonAsciiCount;
return count;
}
//获取指定字符长度字符对应的字符串
- (NSString *)chineseSubStringWithMaxCount:(NSUInteger)maxCount
{
NSUInteger maxCount1 = 2 * maxCount;
NSUInteger count = 0;
NSUInteger index = 0;
for (NSUInteger i = 0; i < self.length; i++) {
unichar c = [self characterAtIndex:i];
if (isascii(c)) {
count++;
} else {
count += 2;
}
if (count == maxCount1) {
index = i + 1;
break;
} else if (count > maxCount1) {
index = i;
break;
}
}
if (index == 0) {
index = self.length;
}
NSString *subString = [self substringToIndex:index];
return subString;
}