How to check whether a string contains whitespaces in between characters?
Asked
Active
Viewed 1.5k times
22
-
Check the following url: http://stackoverflow.com/questions/4645649/remove-whitespace-from-string-in-objective-c – Saranya Dec 05 '11 at 09:15
2 Answers
49
NSString *foo = @"HALLO WELT";
NSRange whiteSpaceRange = [foo rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
if (whiteSpaceRange.location != NSNotFound) {
NSLog(@"Found whitespace");
}
note: this will also find whitespace at the beginning or end of the string. If you don't want this trim the string first...
NSString *trimmedString = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange whiteSpaceRange = [trimmedString rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];

Matthias Bauch
- 89,811
- 20
- 225
- 247
5
You can also follow these steps:
NSArray *componentsSeparatedByWhiteSpace = [testString componentsSeparatedByString:@" "];
If there is any whitespace in your string, then it will separate those and store different components in the array. Now you need to take the count of array. If count is greater than 1, it means there are two components, i.e, presence of white space.
if([componentsSeparatedByWhiteSpace count] > 1){
NSLog(@"Found whitespace");
}

utsabiem
- 920
- 4
- 10
- 21
-
3Be aware that this is very slow. The longer `testString` is, the slower it gets in comparison to the `rangeOfCharacterFromSet:` method I have used. Because I was bored this morning, I compared the performance of both methods and wrote a [blog post](http://matthiasbauch.com/2013/05/26/stackoverflow-how-to-check-whether-a-string-contains-white-spaces/) about it. – Matthias Bauch May 26 '13 at 10:47