如何检查一个string是否包含空格
如何检查string之间是否包含空格?
使用rangeOfCharactersFromSet:
NSString *foo = @"HALLO WELT"; NSRange whiteSpaceRange = [foo rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]]; if (whiteSpaceRange.location != NSNotFound) { NSLog(@"Found whitespace"); }
注意:这也会在string的开头或结尾find空格。 如果你不想这个修剪string…
NSString *trimmedString = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; NSRange whiteSpaceRange = [trimmedString rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
您也可以按照以下步骤操作:
NSArray *componentsSeparatedByWhiteSpace = [testString componentsSeparatedByString:@" "];
如果string中有空格,则会将这些空格分开,并将不同的组件存储在数组中。 现在你需要把数组的数量。 如果count大于1,则意味着有两个组件,即存在空格。
if([componentsSeparatedByWhiteSpace count] > 1){ NSLog(@"Found whitespace"); }