如何在Objective-C中测试NSString是否为空?


当前回答

你可以很容易地检查字符串是否为空:

if ([yourstring isEqualToString:@""]) {
    // execute your action here if string is empty
}

其他回答

只需使用一个if else条件,如下所示:

方法1:

if ([yourString isEqualToString:@""]) {
        // yourString is empty.
    } else {
        // yourString has some text on it.
    }

方法2:

if ([yourString length] == 0) {
    // Empty yourString
} else {
    // yourString is not empty
}

你可以很容易地检查字符串是否为空:

if ([yourstring isEqualToString:@""]) {
    // execute your action here if string is empty
}

斯威夫特版本

即使这是一个Objective C问题,我需要在Swift中使用NSString,所以我也会在这里包括一个答案。

let myNSString: NSString = ""

if myNSString.length == 0 {
    print("String is empty.")
}

或者NSString是可选的:

var myOptionalNSString: NSString? = nil

if myOptionalNSString == nil || myOptionalNSString!.length == 0 {
    print("String is empty.")
}

// or alternatively...
if let myString = myOptionalNSString {
    if myString.length != 0 {
        print("String is not empty.")
    }
}

正常的Swift String版本是

let myString: String = ""

if myString.isEmpty {
    print("String is empty.")
}

请参见:检查Swift中的空字符串?

我检查了一个空字符串使用以下代码:

//Check if we have any search terms in the search dictionary.
if( (strMyString.text==(id) [NSNull null] || [strMyString.text length]==0 
       || strMyString.text isEqual:@"")) {

   [AlertView showAlert:@"Please enter a valid string"];  
}

马克的回答是正确的。但我想借此机会引用Wil Shipley在他的博客上分享的一般化的isEmpty:

static inline BOOL IsEmpty(id thing) {
return thing == nil
|| ([thing respondsToSelector:@selector(length)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:@selector(count)]
&& [(NSArray *)thing count] == 0);
}