Objective-c:包含空格的字符串长度

发布于 2024-12-19 11:32:25 字数 260 浏览 4 评论 0原文

我正在尝试获取字符串中包括空格的字符数。 如果我有一个字符串说:“你好,你好吗?” 我运行这段代码:

 NSUInteger newLength = [myString length];

它返回 15。 但是当你包含空格时有 18 个字符......那么我应该使用什么代码?或者我是否必须运行代码来用星号等字符替换所有空格,计算字符数,然后将字符串设置回原始字符串。这不会太糟糕,除非我必须多次这样做,所以我正在寻找一种更快的方法。谢谢!

I am trying to get the number of characters in a string including spaces.
If I have a string saying: "hello how are you?"
and I run this code:

 NSUInteger newLength = [myString length];

it returns 15.
There are 18 characters though when you include spaces... so what code should I use? Or am I going to have to run code to replace all of the spaces with some character like an asterix, count the number of characters and then set the string back to it's original string. That wouldn't be too bad except I have to do this numerous times so I'm looking for a quicker way. Thanks!

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

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

发布评论

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

评论(3

浪漫人生路 2024-12-26 11:32:25

你能发布你的字符串创建代码吗?我觉得很奇怪。但 NSString length doc 确实说:

接收器中的 Unicode 字符数。

无论如何,您可以获取 c 字符串并使用 strlen,也许这会有所帮助。

size_t length = strlen([myString cStringUsingEncoding:NSUTF8StringEncoding]);

Could you post your string creation code? It seems strange to me. But NSString length doc does say:

The number of Unicode characters in the receiver.

In any case, you could get the c string and use strlen, maybe that would help.

size_t length = strlen([myString cStringUsingEncoding:NSUTF8StringEncoding]);
猫性小仙女 2024-12-26 11:32:25

来自文档..

[string length];   

返回接收器中的 Unicode 字符数。 空格也是一个unicode字符

From the Documentation..

[string length];   

Returns the number of Unicode characters in the receiver. Space is also a unicode character

风追烟花雨 2024-12-26 11:32:25

你用它来获取字符串的长度,包括空格:(

NSUInteger newLength = [myString length];

也就是说,你不应该返回15,而是18)

You use this to get the length of the string, including spaces:

NSUInteger newLength = [myString length];

(that is, you should not be returned 15, but 18)

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