检查NSString是否仅由空格构成

时间:2011-09-01 19:23:09

标签: objective-c string cocoa-touch cocoa nsstring

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

10 个答案:

答案 0 :(得分:104)

NSString *str = @"         ";
NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
if ([[str stringByTrimmingCharactersInSet: set] length] == 0)
{
    // String contains only whitespace.
}

答案 1 :(得分:8)

尝试剥离空格并将其与@“”进行比较:

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

答案 2 :(得分:8)

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

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+上运行测试。 代码here。粘贴到任何XCTestCase子类中。

答案 3 :(得分:2)

试试这个:

[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

答案 4 :(得分:1)

我真的很惊讶我是第一个建议正则表达

的人
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, options:[])
let matches = expression.matches(in: string, options: [], range:NSRange(location: 0, length: string.utf16.count))
let isOnlyWhitespace = !matches.isEmpty

答案 5 :(得分:0)

修剪空格并检查剩余字符数。请看一下这篇文章here

答案 6 :(得分:0)

基于@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

答案 7 :(得分:0)

这里是同样的Swift版本代码,

.git

或者您可以编写如下所示的简单String扩展名,并在多个位置使用相同的代码以提高可读性。

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
    }
}

答案 8 :(得分:0)

必须将此代码用于Swift 3:

func isEmptyOrContainsOnlySpaces() -> Bool {

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

答案 9 :(得分:-1)

这是一个简单的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
}