检查 NSString 是否仅由空格组成
我想检查特定字符串是否仅由空格组成。它可以是任意数量的空格,包括零。确定这一点的最佳方法是什么?
I want to check if a particular string is just made up of spaces. It could be any number of spaces, including zero. What is the best way to determine that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
尝试去掉空格并将其与 @"" 进行比较:
Try stripping it of spaces and comparing it to @"":
检查非空白字符的范围而不是修剪整个字符串要快得多。
请注意,“填充”可能是最常见的混合空格和文本的情况。
测试在我的 iPhone 6+ 上运行。
代码此处。粘贴到任何 XCTestCase 子类中。
It's significantly faster to check for the range of non-whitespace characters instead of trimming the entire string.
Note that "filled" is probably the most common case with a mix of spaces and text.
Tests run on my iPhone 6+.
Code here. Paste into any XCTestCase subclass.
试试这个:
或者
Try this:
or
表达式
或 Swift 的人:
我真的很惊讶我是第一个建议使用正则
I'm really surprised that I am the first who suggests Regular Expression
Or in Swift:
Alternatively
必须在 Swift 3 中使用此代码:
Have to use this code for Swift 3:
修剪空格并检查剩余字符数。看看这篇文章 这里
Trim space and check for number of characters remaining. Take a look at this post here
这是基于 @Alexander Akers 答案的
NSString
上的一个易于重用的类别,但如果字符串包含“新行”,它也会返回YES
...对于那些你们这些不信任的灵魂
..➜
Here is an easily reusable category on
NSString
based on @Alexander Akers' answer, but that also returnsYES
if the string contains "new lines"...and for those of you untrusting souls out there..
➜
这是相同的 Swift 版本代码,
或者您可以编写一个简单的字符串扩展,如下所示,并在多个地方使用具有更好可读性的相同代码。
只需使用这样的任何字符串来调用它,
Here's the Swift version code for the same,
Or you can write a simple String extension like below and use the same code with better readability at multiple places.
and just call it using any string like this,
这是一个简单的 Swift 解决方案:
Here is a simple Swift solution: