如何获得“实际长度” NSString 的

发布于 2024-10-26 15:49:27 字数 162 浏览 2 评论 0原文

假设我有一个字符串,例如:

NSString *str = @"abc一二三";

其中包含英文和中文,如果我使用 [str length] 我得到 结果6.我想要的结果是1+1+1+2+2+2 = 9,一个汉字 等于2个英文字母。

希望有人能帮助我,谢谢^_^

Say I got a string 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^_^

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

魂牵梦绕锁你心扉 2024-11-02 15:49:27

嗯,这会很乏味,但您可以创建自己的字符串长度方法。带有 switch 语句的方法,该方法单独检查字符并相应地分配整数值,然后返回总计。例如:

- (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;
}

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;
}
差↓一点笑了 2024-11-02 15:49:27

也许你可以将 NSString 转换为 NSData,并使用 NSData 的长度。

Maybe you can convert NSString to NSData, and use the length of NSData.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文