2011-09-01 5 views

답변

101
NSString *str = @"   "; 
NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet]; 
if ([[str stringByTrimmingCharactersInSet: set] length] == 0) 
{ 
    // String contains only whitespace. 
} 
+21

상황에 따라 대신에 'whitespaceAndNewlineCharacterSet'을 사용하는 것이 좋습니다 (exa ctly 주석에 쓰여있는 것). – BoltClock

0

공간을 잘라서 남은 문자 수를 확인하십시오. 이 게시물에 봐 것은 here

8

공백을 제거하고 ""@과 비교하십시오 : 여기

[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 

또는

[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
2

이 시도 @Alexander Akers의 답을 바탕으로 NSString에 쉽게 재사용 할 수있는 카테고리이지만,

@interface NSString (WhiteSpaceDetect) 
@property (readonly) BOOL isOnlyWhitespace; 
@end 
@implementation NSString (WhiteSpaceDetect) 
- (BOOL) isOnlyWhitespace { 
    return ![self stringByTrimmingCharactersInSet: 
      [NSCharacterSet whitespaceAndNewlineCharacterSet]].length; 
} 
@end 

하고 거기에 당신 untrusting 영혼의 사람들을 위해

..

#define WHITE_TEST(x) for (id z in x) printf("\"%s\" : %s\n",[z UTF8String], [z isOnlyWhitespace] ? "YES" :"NO") 

WHITE_TEST(({ @[ 

    @"Applebottom", 
    @"jeans\n", 
    @"\n", 
    @"" 
    "", 
    @" \ 
    \ 
    ", 
    @" " 
];})); 
여기
"Applebottom" : NO 
"jeans 
" : NO 
" 
" : YES 
"" : YES 
" " : YES 
" " : YES 
+0

이것은 'NSMutableString' 메소드입니다. –

+5

음, 아니야. 새 NSString을 반환하고 NSString.h에 선언됩니다. – picciano

+0

실제로 어디에도 정의되어 있지 않습니다. –

0

:

NSString *probablyEmpty = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
BOOL wereOnlySpaces = [probablyEmpty isEqualToString:@""]; 
-1

간단 ... YES 문자열이 "새로운 라인"을 포함하는 경우 반환 신속한 해결책 :

//Check if string contains only empty spaces and new line characters 
static func isStringEmpty(#text: String) -> Bool { 
    let characterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet() 
    let newText = text.stringByTrimmingCharactersInSet(characterSet) 
    return newText.isEmpty 
} 
+0

이유 투표? – Esqarrouth

-1

여기

var str = "Hello World" 
if count(str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())) == 0 { 
    // String is empty or contains only white spaces 
} 
else { 
    // String is not empty and contains other characters 
} 

, 동일한에 대한 스위프트의 버전 코드의 또는 당신은 다음과 같은 간단한 문자열 확장을 작성하고 여러 장소에서 가독성과 같은 코드를 사용할 수 있습니다.

extension String { 
    func isEmptyOrContainsOnlySpaces() -> Bool { 
     return count(self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())) == 0 
    } 
} 

그냥 같은 문자열을 사용하여 전화

, 대신 전체 문자열을 트리밍의 공백이 아닌 문자의 범위를 확인하기 위해 훨씬 더 빠른

var str1 = " " 
if str.isEmptyOrContainsOnlySpaces() { 
    // custom code e.g Show an alert 
} 
7

.

NSCharacterSet *inverted = [[NSCharacterSet whitespaceAndNewlineCharacterSet] invertedSet]; 
NSRange range = [string rangeOfCharacterFromSet:inverted]; 
BOOL empty = (range.location == NSNotFound); 

"채우기"는 공백과 텍스트가 혼합 된 가장 일반적인 경우 일 수 있습니다.

testSpeedOfSearchFilled - 0.012 sec 
testSpeedOfTrimFilled - 0.475 sec 
testSpeedOfSearchEmpty - 1.794 sec 
testSpeedOfTrimEmpty - 3.032 sec 

테스트는 iPhone 6 이상에서 실행됩니다. 코드 here. 모든 XCTestCase 하위 클래스에 붙여 넣습니다.

+2

이 답변이 훨씬 좋습니다. 많은 사람들이 맹목적으로 솔루션을 다듬기 위해 갔다는 사실에 정말 놀랐습니다. 그러나 오타를 수정해야합니다. range.location! = NSNotFound 인 경우 문자열이 비어 있지 않음을 의미하는 non-WS char가 있음을 의미합니다. 그래서 조건을 뒤집을 필요가 있습니다. – battlmonstr

0

는 스위프트 3이 코드를 사용해야합니다 :

func isEmptyOrContainsOnlySpaces() -> Bool { 

    return self.trimmingCharacters(in: .whitespaces).characters.count == 0 
} 
0

내가 알 수있는 첫 번째임을 정말 놀랐어요를 정규 표현식

NSString *string = @"   "; 
NSString *pattern = @"^\\s*$"; 
NSRegularExpression *expression = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil]; 
NSArray *matches = [expression matchesInString:string options:0 range:NSMakeRange(0, string.length)]; 
BOOL isOnlyWhitespace = matches.count; 

또는 스위프트의 :

let string = "   " 
let pattern = "^\\s*$" 
let expression = try! NSRegularExpression(pattern:pattern, options:[]) 
let matches = expression.matches(in: string, options: [], range:NSRange(location: 0, length: string.utf16.count)) 
let isOnlyWhitespace = !matches.isEmpty 
관련 문제