2011-12-05 104 views

回答

46

使用rangeOfCharactersFromSet:

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

您也可以按照下列步骤操作:

NSArray *componentsSeparatedByWhiteSpace = [testString componentsSeparatedByString:@" "]; 

如果在你的字符串中的任何空白,那么它将把这些分开和在数组中存储不同的组件。现在你需要获取数组的数量。如果count大于1,则意味着有两个组件,即存在空白区域。

if([componentsSeparatedByWhiteSpace count] > 1){ 
    NSLog(@"Found whitespace"); 
} 
+3

要知道,这是非常缓慢的。与'rangeOfCharacterFromSet:'方法相比,'testString'的长度越长,它所得到的速度就越慢。因为今天早上我很无聊,我比较了两种方法的表现,并写了一篇[博客文章](http://matthiasbauch.com/2013/05/26/stackoverflow-how-to-check-whether-a-string-包含白色空间/)关于它。 –

相关问题