【发布时间】:2011-12-05 09:12:55
【问题描述】:
如何检查字符串中字符之间是否包含空格?
【问题讨论】:
标签: iphone ios nsstring whitespace
如何检查字符串中字符之间是否包含空格?
【问题讨论】:
标签: iphone ios nsstring whitespace
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:@" "];
如果您的字符串中有任何空格,那么它将分隔这些空格并将不同的组件存储在数组中。现在您需要计算数组的数量。如果 count 大于 1,则表示有两个分量,即存在空白。
if([componentsSeparatedByWhiteSpace count] > 1){
NSLog(@"Found whitespace");
}
【讨论】:
testString 越长,与我使用的 rangeOfCharacterFromSet: 方法相比,它变得越慢。因为今天早上比较无聊,对比了两种方法的性能,写了blog post。