How to check whether a string contains whitespaces in between characters?
如何检查字符串是否在字符之间包含空格?
2 个解决方案
#1
48
使用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
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.
如果字符串中有任何空格,那么它将分隔这些空格并在数组中存储不同的组件。现在你需要计算数组。如果count大于1,则意味着有两个组件,即存在空白区域。
if([componentsSeparatedByWhiteSpace count] > 1){
NSLog(@"Found whitespace");
}
#1
48
使用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
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.
如果字符串中有任何空格,那么它将分隔这些空格并在数组中存储不同的组件。现在你需要计算数组。如果count大于1,则意味着有两个组件,即存在空白区域。
if([componentsSeparatedByWhiteSpace count] > 1){
NSLog(@"Found whitespace");
}