2011-12-05 4 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より大きい場合、2つの成分、すなわち空白の存在があることを意味する。

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

。 'testString'が長いほど、私が使用した' rangeOfCharacterFromSet: 'メソッドと比較して遅くなります。私は今朝退屈だったので、私は両方の方法の性能を比較し、[ブログの投稿]を書いた(http://matthiasbauch.com/2013/05/26/stackoverflow-how-to-check-whether-a-string-含まれている白いスペース/)。 –

関連する問題