Objective C 如何检测 NSString 中的一个或多个空格
我已经看到了我的任务的一个答案,但现在找不到了。 我想检测一个字符串是否有空单词并且至少包含“”或“”(两个空格)或多个空格,或者不包含。 如果没有,我会将其添加到 Nsmutablearray 中。 如果是,并且有空或至少一个空格,我希望它不要写入可变数组。
怎么解决这个问题呢?
编辑 2011 年 10 月 12 日:
伙计们,谢谢你们。
再次抱歉,我不清楚我的愿望。我想检查字符串是否为空或包含没有任何字符的空格。我已在下面发布了我的答案。
I have seen one answer for my task, but I couldnt find it now.
I want to detect whether a string has empty word and contains at least "" or " " (two spaces" or more multiple spaces, OR not.
If not, I would add this to Nsmutablearray.
If yes with empty or at least one space, I would like it not to be written to mutablearray.
How to solve this?
EDIT 12 October 2011:
Guys, thank you.
Again I am sorry that I was unclear about my wish. I wanted to check if a string is empty or contains whitespaces without any character. I have posted my answer below.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
看一下 NSRegularExpression类和编码示例。
Take a look at the NSRegularExpression class and coding examples.
我不确定这是否是最有效的方法,但您可以拆分数组并查看长度是否大于 1:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
Im not sure whether it is the most performant way of doing it but you could split your array and see whether the length is greater than 1:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
取决于您是否正在寻找任何空白或只是空格。对于可以使用的空格:
如果有空格,请使用空格字符集:
如果您愿意,请将
whitespaceCharacterSet
替换为whitespaceAndNewlineCharacterSet
。Depends if you're looking for ANY whitespace or just spaces. For spaces you can use:
If any whitespace, use the whitespace character set:
Replace
whitespaceCharacterSet
withwhitespaceAndNewlineCharacterSet
if you like.查看文档 代表
NSString
。具体来说,请在查找字符和子字符串部分中查找您想要的方法,可能您希望多次使用
– rangeOfString:options:range:
。另外,请在替换子字符串部分下查找您想要的方法,可能您想使用
– stringByReplacingOccurrencesOfString:withString:options:range:
Look at the documentation for
NSString
.Specifically, look under the section Finding Characters and Substrings for the method you want, probably you want to use
– rangeOfString:options:range:
multiple times.Also, look under the section Replacing Substrings for the method you want, probably you want to use
– stringByReplacingOccurrencesOfString:withString:options:range: