Check if an NSString is just made out of spaces

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?


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

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

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

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.

链接地址: http://www.djcxy.com/p/85228.html

上一篇: 有没有办法计算NSString的行数?

下一篇: 检查一个NSString是否仅仅由空格组成