How to check whether a string contains white spaces

雨燕双飞 提交于 2019-12-03 10:58:18

问题


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


回答1:


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]];



回答2:


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");
}


来源:https://stackoverflow.com/questions/8383034/how-to-check-whether-a-string-contains-white-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!