Check if an NSString is just made out of spaces
Solution 1
NSString *str = @" ";
NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
if ([[str stringByTrimmingCharactersInSet: set] length] == 0)
{
// String contains only whitespace.
}
Solution 2
Try stripping it of spaces and comparing it to @"":
NSString *probablyEmpty = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
BOOL wereOnlySpaces = [probablyEmpty isEqualToString:@""];
Solution 3
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.
Solution 4
Try this:
[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
or
[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Solution 5
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
Suchi
I am an Android and iOS Developer, but have dabbled in a variety of other software programming. Love to explore new technologies and discuss n debate about them :)
Updated on June 06, 2022Comments
-
Suchi almost 2 years
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?
-
BoltClock over 12 yearsDepending on the situation one may want to use
whitespaceAndNewlineCharacterSet
instead (does exactly what it says on the tin). -
Alexsander Akers over 12 yearsThis is an
NSMutableString
method. -
picciano over 12 yearsUm, no it's not. It returns a new NSString and is declared in NSString.h.
-
Alexsander Akers over 12 yearsActually it isn't defined anywhere.