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?
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.
Try this:
[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
or
[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Have to use this code for Swift 3:
func isEmptyOrContainsOnlySpaces() -> Bool {
return self.trimmingCharacters(in: .whitespaces).characters.count == 0
}
NSString *str = @" ";
NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
if ([[str stringByTrimmingCharactersInSet: set] length] == 0)
{
// String contains only whitespace.
}