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


当前回答

你有两个方法来检查字符串是否为空:

让我们假设你的字符串名字是NSString *strIsEmpty。

方法1:

if(strIsEmpty.length==0)
{
    //String is empty
}

else
{
    //String is not empty
}

方法2:

if([strIsEmpty isEqualToString:@""])
{
    //String is empty
}

else
{
    //String is not empty
}

选择上述任何一种方法,了解字符串是否为空。

其他回答

空字符串有两种方式:

1) @"" //不包含空格

2) @" " //包含空格

严格来说,这两个字符串都是空的。我们可以用条件一来写出这两个式子

if ([firstNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""].length==0)
{
    NSLog(@"Empty String");
}
else
{
    NSLog(@"String contains some value");
}

只需使用一个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
}

试试下面的方法

NSString *stringToCheck = @"";

if ([stringToCheck isEqualToString:@""])
{
   NSLog(@"String Empty");
}
else
{
   NSLog(@"String Not Empty");
}
if (string.length == 0) stringIsEmpty;

我这样写:

@implementation NSObject (AdditionalMethod)
-(BOOL) isNotEmpty
{
    return !(self == nil
    || [self isKindOfClass:[NSNull class]]
    || ([self respondsToSelector:@selector(length)]
        && [(NSData *)self length] == 0)
    || ([self respondsToSelector:@selector(count)]
        && [(NSArray *)self count] == 0));

};
@end

问题是如果self为nil,这个函数就永远不会被调用。它将返回false,这是所期望的。