如何检查字符串中是否包含字符之间的空格?
如何检查字符串中是否包含字符之间的空格?
NSString *foo = @"HALLO WELT";
NSRange whiteSpaceRange = [foo rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
if (whiteSpaceRange.location != NSNotFound) {
NSLog(@"Found whitespace");
}
注意:这也会发现字符串开头或结尾的空格。如果您不想要这个,请先修整字符串...
NSString *trimmedString = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange whiteSpaceRange = [trimmedString rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *componentsSeparatedByWhiteSpace = [testString componentsSeparatedByString:@" "];
如果您的字符串中有任何空格,它将把它们分隔并在数组中存储不同的组件。现在您需要获取数组的数量。如果计数大于1,则表示有两个组件,即存在空格。
if([componentsSeparatedByWhiteSpace count] > 1){
NSLog(@"Found whitespace");
}
testString
越长,与我使用的 rangeOfCharacterFromSet:
方法相比,执行速度就越慢。因为今天早上我感到无聊,所以比较了两种方法的性能并写了一篇博客文章。 - Matthias Bauch