检查 NSString 是否仅由空格组成

发布于 2024-12-02 07:33:14 字数 55 浏览 1 评论 0原文

我想检查特定字符串是否仅由空格组成。它可以是任意数量的空格,包括零。确定这一点的最佳方法是什么?

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 技术交流群。

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

发布评论

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

评论(10

-柠檬树下少年和吉他 2024-12-09 07:33:14
NSString *str = @"         ";
NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
if ([[str stringByTrimmingCharactersInSet: set] length] == 0)
{
    // String contains only whitespace.
}
NSString *str = @"         ";
NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
if ([[str stringByTrimmingCharactersInSet: set] length] == 0)
{
    // String contains only whitespace.
}
疧_╮線 2024-12-09 07:33:14

尝试去掉空格并将其与 @"" 进行比较:

NSString *probablyEmpty = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
BOOL wereOnlySpaces = [probablyEmpty isEqualToString:@""];

Try stripping it of spaces and comparing it to @"":

NSString *probablyEmpty = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
BOOL wereOnlySpaces = [probablyEmpty isEqualToString:@""];
听,心雨的声音 2024-12-09 07:33:14

检查非空白字符的范围而不是修剪整个字符串要快得多。

NSCharacterSet *inverted = [[NSCharacterSet whitespaceAndNewlineCharacterSet] invertedSet];
NSRange range = [string rangeOfCharacterFromSet:inverted];
BOOL empty = (range.location == NSNotFound);

请注意,“填充”可能是最常见的混合空格和文本的情况。

testSpeedOfSearchFilled - 0.012 sec
testSpeedOfTrimFilled - 0.475 sec
testSpeedOfSearchEmpty - 1.794 sec
testSpeedOfTrimEmpty - 3.032 sec

测试在我的 iPhone 6+ 上运行。
代码此处。粘贴到任何 XCTestCase 子类中。

It's significantly faster to check for the range of non-whitespace characters instead of trimming the entire string.

NSCharacterSet *inverted = [[NSCharacterSet whitespaceAndNewlineCharacterSet] invertedSet];
NSRange range = [string rangeOfCharacterFromSet:inverted];
BOOL empty = (range.location == NSNotFound);

Note that "filled" is probably the most common case with a mix of spaces and text.

testSpeedOfSearchFilled - 0.012 sec
testSpeedOfTrimFilled - 0.475 sec
testSpeedOfSearchEmpty - 1.794 sec
testSpeedOfTrimEmpty - 3.032 sec

Tests run on my iPhone 6+.
Code here. Paste into any XCTestCase subclass.

趁年轻赶紧闹 2024-12-09 07:33:14

试试这个:

[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

或者

[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Try this:

[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

or

[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
纵山崖 2024-12-09 07:33:14

表达式

NSString *string = @"         ";
NSString *pattern = @"^\\s*$";
NSRegularExpression *expression = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
NSArray *matches = [expression matchesInString:string options:0 range:NSMakeRange(0, string.length)];
BOOL isOnlyWhitespace = matches.count;

或 Swift 的人:

let string = "         "
let pattern = "^\\s*$"
let expression = try! NSRegularExpression(pattern:pattern)
let matches = expression.matches(in: string, range: NSRange(string.startIndex..., in: string))
let isOnlyWhitespace = !matches.isEmpty

我真的很惊讶我是第一个建议使用正则

let string = "         "
let isOnlyWhitespace = string.range(of: "^\\s*$", options: .regularExpression) != nil

I'm really surprised that I am the first who suggests Regular Expression

NSString *string = @"         ";
NSString *pattern = @"^\\s*$";
NSRegularExpression *expression = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
NSArray *matches = [expression matchesInString:string options:0 range:NSMakeRange(0, string.length)];
BOOL isOnlyWhitespace = matches.count;

Or in Swift:

let string = "         "
let pattern = "^\\s*$"
let expression = try! NSRegularExpression(pattern:pattern)
let matches = expression.matches(in: string, range: NSRange(string.startIndex..., in: string))
let isOnlyWhitespace = !matches.isEmpty

Alternatively

let string = "         "
let isOnlyWhitespace = string.range(of: "^\\s*$", options: .regularExpression) != nil
⊕婉儿 2024-12-09 07:33:14

必须在 Swift 3 中使用此代码:

func isEmptyOrContainsOnlySpaces() -> Bool {

    return self.trimmingCharacters(in: .whitespaces).characters.count == 0
}

Have to use this code for Swift 3:

func isEmptyOrContainsOnlySpaces() -> Bool {

    return self.trimmingCharacters(in: .whitespaces).characters.count == 0
}
一身软味 2024-12-09 07:33:14

修剪空格并检查剩余字符数。看看这篇文章 这里

Trim space and check for number of characters remaining. Take a look at this post here

御弟哥哥 2024-12-09 07:33:14

这是基于 @Alexander Akers 答案的 NSString 上的一个易于重用的类别,但如果字符串包含“新行”,它也会返回 YES...

@interface NSString (WhiteSpaceDetect)
@property (readonly) BOOL isOnlyWhitespace;
@end
@implementation NSString (WhiteSpaceDetect)
- (BOOL) isOnlyWhitespace { 
  return ![self stringByTrimmingCharactersInSet:
          [NSCharacterSet whitespaceAndNewlineCharacterSet]].length;
}
@end

对于那些你们这些不信任的灵魂

#define WHITE_TEST(x) for (id z in x) printf("\"%s\" : %s\n",[z UTF8String], [z isOnlyWhitespace] ? "YES" :"NO")

WHITE_TEST(({ @[

    @"Applebottom",
    @"jeans\n",
    @"\n",
    @""
    "",
    @"   \
    \
    ",
    @"   "
];}));

..➜

"Applebottom" : NO
"jeans
" : NO
"
" : YES
"" : YES
"   " : YES
"   " : YES

Here is an easily reusable category on NSString based on @Alexander Akers' answer, but that also returns YES if the string contains "new lines"...

@interface NSString (WhiteSpaceDetect)
@property (readonly) BOOL isOnlyWhitespace;
@end
@implementation NSString (WhiteSpaceDetect)
- (BOOL) isOnlyWhitespace { 
  return ![self stringByTrimmingCharactersInSet:
          [NSCharacterSet whitespaceAndNewlineCharacterSet]].length;
}
@end

and for those of you untrusting souls out there..

#define WHITE_TEST(x) for (id z in x) printf("\"%s\" : %s\n",[z UTF8String], [z isOnlyWhitespace] ? "YES" :"NO")

WHITE_TEST(({ @[

    @"Applebottom",
    @"jeans\n",
    @"\n",
    @""
    "",
    @"   \
    \
    ",
    @"   "
];}));

"Applebottom" : NO
"jeans
" : NO
"
" : YES
"" : YES
"   " : YES
"   " : YES
眉目亦如画i 2024-12-09 07:33:14

这是相同的 Swift 版本代码,

var str = "Hello World" 
if count(str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())) == 0 {
     // String is empty or contains only white spaces
}
else {
    // String is not empty and contains other characters
}

或者您可以编写一个简单的字符串扩展,如下所示,并在多个地方使用具有更好可读性的相同代码。

extension String {
    func isEmptyOrContainsOnlySpaces() -> Bool {
        return count(self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())) == 0
    }
}

只需使用这样的任何字符串来调用它,

var str1 = "   "
if str.isEmptyOrContainsOnlySpaces() {
    // custom code e.g Show an alert
}

Here's the Swift version code for the same,

var str = "Hello World" 
if count(str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())) == 0 {
     // String is empty or contains only white spaces
}
else {
    // String is not empty and contains other characters
}

Or you can write a simple String extension like below and use the same code with better readability at multiple places.

extension String {
    func isEmptyOrContainsOnlySpaces() -> Bool {
        return count(self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())) == 0
    }
}

and just call it using any string like this,

var str1 = "   "
if str.isEmptyOrContainsOnlySpaces() {
    // custom code e.g Show an alert
}
〃温暖了心ぐ 2024-12-09 07:33:14

这是一个简单的 Swift 解决方案:

//Check if string contains only empty spaces and new line characters
static func isStringEmpty(#text: String) -> Bool {
    let characterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
    let newText = text.stringByTrimmingCharactersInSet(characterSet)
    return newText.isEmpty
}

Here is a simple Swift solution:

//Check if string contains only empty spaces and new line characters
static func isStringEmpty(#text: String) -> Bool {
    let characterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
    let newText = text.stringByTrimmingCharactersInSet(characterSet)
    return newText.isEmpty
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文