49

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?

Charles
  • 50,943
  • 13
  • 104
  • 142
Suchi
  • 9,989
  • 23
  • 68
  • 112

10 Answers10

107
NSString *str = @"         ";
NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
if ([[str stringByTrimmingCharactersInSet: set] length] == 0)
{
    // String contains only whitespace.
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Alexsander Akers
  • 15,967
  • 12
  • 58
  • 83
  • 22
    Depending on the situation one may want to use `whitespaceAndNewlineCharacterSet` instead (does exactly what it says on the tin). – BoltClock Sep 01 '11 at 19:27
9

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.

arsenius
  • 12,090
  • 7
  • 58
  • 76
9

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

NSString *probablyEmpty = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
BOOL wereOnlySpaces = [probablyEmpty isEqualToString:@""];
Eimantas
  • 48,927
  • 17
  • 132
  • 168
2

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
vadian
  • 274,689
  • 30
  • 353
  • 361
2

Try this:

[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

or

[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Greg
  • 33,450
  • 15
  • 93
  • 100
picciano
  • 22,341
  • 9
  • 69
  • 82
1

Have to use this code for Swift 3:

func isEmptyOrContainsOnlySpaces() -> Bool {

    return self.trimmingCharacters(in: .whitespaces).characters.count == 0
}
alexmorhun
  • 1,903
  • 2
  • 18
  • 23
0

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
Alex Gray
  • 16,007
  • 9
  • 96
  • 118
0

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
}
Rameswar Prasad
  • 1,331
  • 17
  • 35
0

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

Community
  • 1
  • 1
James Raitsev
  • 92,517
  • 154
  • 335
  • 470
-1

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
}
Esqarrouth
  • 38,543
  • 21
  • 161
  • 168