How to check whether a string contains white space

2019-03-14 19:38发布

How to check whether a string contains whitespaces in between characters?

2条回答
来,给爷笑一个
2楼-- · 2019-03-14 20:18

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");
}
查看更多
萌系小妹纸
3楼-- · 2019-03-14 20:25

use rangeOfCharactersFromSet:

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]];
查看更多
登录 后发表回答