如何清理 NSString 中的空格

发布于 2024-09-08 19:42:19 字数 303 浏览 14 评论 0原文

我想将 NSString(Objective-C/iPhone dev)中两个单词之间的空格数量减少到只有一个。你知道有什么方法可以做到这一点吗?

示例:

清洁前:“嗨,     我的  名字      是              汤姆。”
清洁后:“嗨,我叫汤姆。”

谢谢

I would like to reduce the number of spaces between two words in a NSString (Objective-C/iPhone dev) to only one. Do you know some method that could do that ?

Exemple :

Before cleaning : "Hi,       my   name       is                Tom."
After cleaning : "Hi, my name is Tom."

Thanks

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

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

发布评论

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

评论(3

开始看清了 2024-09-15 19:42:19

使用 [mystring ComponentsSeparatedByString:@" "] 获取由单个空格分隔的所有子字符串的 NSArray。然后,重新组合数组中的非空字符串,得到最终的字符串。

Use [mystring componentsSeparatedByString:@" "] to get a NSArray of all substrings separated by a single space. Then, recombine the non-empty strings in the array to get the final string.

仙女 2024-09-15 19:42:19

看看 http://regexkit.sourceforge.net/,它有 NSString 扩展,您可以使用它进行基于正则表达式的字符串替换。

Take a look at http://regexkit.sourceforge.net/, it has NSString extensions with which you could do regex-based string replace.

娇纵 2024-09-15 19:42:19

使用 RegexKit,添加到 RSC 的答案

NSString *subjectString     = @"Hi,       my   name       is                Tom.";
NSString *regexString       = @"(\\s+)";
NSString *replacementString = @" ";

NSString *newString = [subjectString stringByMatching:regexString replace:RKReplaceAll withString:replacementString];

using RegexKit, adding to RSC's answer

NSString *subjectString     = @"Hi,       my   name       is                Tom.";
NSString *regexString       = @"(\\s+)";
NSString *replacementString = @" ";

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