Alb*_*haw 5 string glyph objective-c string-length charactercount
在objective-c中的字符串中,如果我说类似[myStr length];它返回一个数字,这是一个字节数,但我可以用什么来返回字符串中的字符数.
例如:
一个字母"a"
的字符串返回长度为1
的字符串,其中包含一个表情符号,返回长度为2(有时甚至长度为4)
这是因为这是字符串中的字节数...我只需要字符数.
我只是掀起了这个方法.将其添加到NSString类别中.
- (NSUInteger)characterCount {
NSUInteger cnt = 0;
NSUInteger index = 0;
while (index < self.length) {
NSRange range = [self rangeOfComposedCharacterSequenceAtIndex:index];
cnt++;
index += range.length;
}
return cnt;
}
NSString *a = @"Hello";
NSLog(@"%@ length = %u, chars = %u", a, a.length, a.characterCount);
NSString *b = @" Emoji ";
NSLog(@"%@ length = %u, chars = %u", b, b.length, b.characterCount);
Run Code Online (Sandbox Code Playgroud)
这会产生:
你好长度= 5,字符= 5
表情符号长度= 11,字符= 9
| 归档时间: |
|
| 查看次数: |
2378 次 |
| 最近记录: |