2011-12-05 10 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

. 'testString'이 길수록, 제가 사용했던'rangeOfCharacterFromSet :'메소드에 비해 속도가 느려집니다. 내가 오늘 아침 지루했기 때문에 두 방법의 성능을 비교하고 [블로그 게시물]을 썼습니다. (http://matthiasbauch.com/2013/05/26/stackoverflow-how-to-check-whether-a-string- 포함 - 화이트 스페이스 /). –

관련 문제