在Objective C中如何测试字符串是否为空?

时间:2022-05-27 08:09:00

How do I test if an NSString is empty in Objective C?

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

29 个解决方案

#1


1082  

You can check if [string length] == 0. This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length on nil will also return 0.

您可以检查[string length]是否= 0。这将检查它是否是一个有效的空字符串(@""),如果它是nil,因为在nil上调用length也会返回0。

#2


126  

Marc's answer is correct. But I'll take this opportunity to include a pointer to Wil Shipley's generalized isEmpty, which he shared on his blog:

马克的回答是正确的。但是,我想借此机会介绍一下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);
}

#3


92  

The first approach is valid, but doesn't work if your string has blank spaces (@" "). So you must clear this white spaces before testing it.

第一种方法是有效的,但是如果您的字符串有空格(@“”),则不能使用。因此,在测试之前,您必须清除这些空白。

This code clear all the blank spaces on both sides of the string:

此代码清除字符串两边的所有空格:

[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];

One good idea is create one macro, so you don't have to type this monster line:

一个好主意是创建一个宏,所以你不必输入这个怪物行:

#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]

Now you can use:

现在您可以使用:

NSString *emptyString = @"   ";

if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");

#4


30  

One of the best solution I ever seen (better than Matt G's one) is this improved inline function I picked up on some Git Hub repo (Wil Shipley's one, but I can't find the link) :

我所见过的最好的解决方案之一(比Matt G的更好)是我在Git Hub repo上获得的这个改进的内联函数(Wil Shipley的那个,但我找不到链接):

// Check if the "thing" pass'd is empty
static inline BOOL isEmpty(id thing) {
    return thing == nil
    || [thing isKindOfClass:[NSNull class]]
    || ([thing respondsToSelector:@selector(length)]
        && [(NSData *)thing length] == 0)
    || ([thing respondsToSelector:@selector(count)]
        && [(NSArray *)thing count] == 0);
}

#5


14  

You should better use this category:

你最好使用这个类别:

@implementation NSString (Empty)

    - (BOOL) isWhitespace{
        return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);
    }

@end

#6


12  

Just pass your string to following method:

只需将字符串传递给以下方法:

+(BOOL)isEmpty:(NSString *)str
{
    if(str.length==0 || [str isKindOfClass:[NSNull class]] || [str isEqualToString:@""]||[str  isEqualToString:NULL]||[str isEqualToString:@"(null)"]||str==nil || [str isEqualToString:@"<null>"]){
        return YES;
    }
    return NO;
}

#7


11  

I put this:

我把这个:

@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

The problem is that if self is nil, this function is never called. It'll return false, which is desired.

问题是如果self是nil,这个函数就不会被调用。它会返回false。

#8


9  

Another option is to check if it is equal to @"" with isEqualToString: like so:

另一个选项是用isEqualToString检查它是否等于@":like so:

if ([myString isEqualToString:@""]) {
    NSLog(@"myString IS empty!");
} else {
    NSLog(@"myString IS NOT empty, it is: %@", myString);
}

#9


5  

Just use one of the if else conditions as shown below:

使用if else条件,如下所示:

Method 1:

方法1:

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

Method 2:

方法2:

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

#10


5  

Swift Version

Even though this is an Objective C question, I needed to use NSString in Swift so I will also include an answer here.

尽管这是一个客观的C问题,但我需要在Swift中使用NSString,因此我将在这里包含一个答案。

let myNSString: NSString = ""

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

Or if NSString is an Optional:

或者如果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.")
    }
}

The normal Swift String version is

普通的Swift字符串版本是

let myString: String = ""

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

See also: Check empty string in Swift?

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

#11


5  

May be this answer is the duplicate of already given answers, but i did few modification and changes in the order of checking the conditions. Please refer the below code:

可能这个答案是已经给出答案的重复,但是我在检查条件的顺序上做了一些修改和修改。请参考以下代码:

+(BOOL)isStringEmpty:(NSString *)str
    {
        if(str == nil || [str isKindOfClass:[NSNull class]] || str.length==0) {
            return YES;
       }
        return NO;
    }

#12


4  

You can check either your string is empty or not my using this method:

你可以用这个方法检查你的字符串是否为空:

+(BOOL) isEmptyString : (NSString *)string
{
    if([string length] == 0 || [string isKindOfClass:[NSNull class]] || 
       [string isEqualToString:@""]||[string  isEqualToString:NULL]  ||
       string == nil)
     {
        return YES;         //IF String Is An Empty String
     }
    return NO;
}

Best practice is to make a shared class say UtilityClass and ad this method so that you would be able to use this method by just calling it through out your application.

最佳实践是创建一个共享类,比如实用类和这个方法,这样您就可以通过调用应用程序来使用这个方法。

#13


4  

You have 2 methods to check whether the string is empty or not:

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

Let's suppose your string name is NSString *strIsEmpty.

假设您的字符串名称是NSString *strIsEmpty。

Method 1:

方法1:

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

else
{
    //String is not empty
}

Method 2:

方法2:

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

else
{
    //String is not empty
}

Choose any of the above method and get to know whether string is empty or not.

选择上面的任何一个方法,并了解字符串是否为空。

#14


3  

Very useful post, to add NSDictionary support as well one small change

非常有用的贴子,添加NSDictionary支持以及一个小改变

static inline BOOL isEmpty(id thing) {
    return thing == nil
    || [thing isKindOfClass:[NSNull class]]
    || ([thing respondsToSelector:@selector(length)]
        && ![thing respondsToSelector:@selector(count)]
        && [(NSData *)thing length] == 0)
    || ([thing respondsToSelector:@selector(count)]
        && [thing count] == 0);
}

#15


3  

Simply Check your string length

只需检查字符串长度

 if (!yourString.length)
 {
   //your code  
 }

a message to NIL will return nil or 0, so no need to test for nil :).

发送到NIL的消息将返回NIL或0,因此不需要测试NIL:)。

Happy coding ...

快乐的编码…

#16


2  

It is working as charm for me

它对我很有吸引力

If the NSString is s

如果NSString是s

if ([s isKindOfClass:[NSNull class]] || s == nil || [s isEqualToString:@""]) {

    NSLog(@"s is empty");

} else {

    NSLog(@"s containing %@", s);

}

#17


2  

So aside from the basic concept of checking for a string length less than 1, it is important to consider context deeply. Languages human or computer or otherwise might have different definitions of empty strings and within those same languages, additional context may further change the meaning.

因此,除了检查小于1的字符串长度的基本概念之外,深入考虑上下文是很重要的。语言、人或计算机或其他可能对空字符串有不同的定义,在相同的语言中,附加的上下文可能会进一步改变其含义。

Let's say empty string means "a string which does not contain any characters significant in the current context".

假设空字符串表示“不包含当前上下文中任何重要字符的字符串”。

This could mean visually, as in color and background color are same in an attributed string. Effectively empty.

这可能意味着在视觉上,就像颜色和背景颜色在带属性字符串中是一样的。有效的空。

This could mean empty of meaningful characters. All dots or all dashes or all underscores might be considered empty. Further, empty of meaningful significant characters could mean a string that has no characters the reader understands. They could be characters in a language or characterSet defined as meaningless to the reader. We could define it a little differently to say the string forms no known words in a given language.

这可能意味着没有有意义的字符。所有的点或所有的破折号或所有的下划线可能被认为是空的。此外,没有意义的重要字符可能意味着没有读者理解的字符的字符串。它们可以是语言中的字符或被定义为对读者没有意义的字符集。我们可以用一种不同的方式来定义这个字符串在给定的语言中不存在已知的单词。

We could say empty is a function of the percentage of negative space in the glyphs rendered.

我们可以说,空是所渲染的符号中负空间百分比的函数。

Even a sequence of non printable characters with no general visual representation is not truly empty. Control characters come to mind. Especially the low ASCII range (I'm surprised nobody mentioned those as they hose lots of systems and are not whitespace as they normally have no glyphs and no visual metrics). Yet the string length is not zero.

即使是不具有一般视觉表示的不可打印字符序列也不是真正的空。我想到了控制角色。特别是低ASCII范围(我很惊讶没有人提到它们,因为它们连接了很多系统,而且不是空白,因为它们通常没有符号和视觉度量)。但是字符串长度不是0。

Conclusion. Length alone is not the only measure here. Contextual set membership is also pretty important.

结论。长度本身并不是唯一的衡量标准。上下文集成员关系也很重要。

Character Set membership is a very important common additional measure. Meaningful sequences are also a fairly common one. ( think SETI or crypto or captchas ) Additional more abstract context sets also exist.

字符集隶属度是一种非常重要的常用附加度量。有意义的序列也是相当常见的。(想想SETI或crypto或captchas)还有更多的抽象上下文集。

So think carefully before assuming a string is only empty based on length or whitespace.

因此,在假设字符串仅为空时,请仔细考虑。

#18


2  

- (BOOL)isEmpty:(NSString *)string{
    if ((NSNull *) string == [NSNull null]) {
        return YES;
    }
    if (string == nil) {
        return YES;
    }
    if ([string length] == 0) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
        return YES;
    }
    if([[string stringByStrippingWhitespace] isEqualToString:@""]){
        return YES;
    }
    return NO;
}

#19


2  

The best way is to use the category.
You can check the following function. Which has all the conditions to check.

最好的方法是使用这个类别。您可以检查以下函数。它有所有的条件去检查。

-(BOOL)isNullString:(NSString *)aStr{
        if([(NSNull *)aStr isKindOfClass:[NSNull class]]){
            return YES;
        }
        if ((NSNull *)aStr  == [NSNull null]) {
            return YES;
        }
        if ([aStr isKindOfClass:[NSNull class]]){
            return YES;
        }
        if(![[aStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]){
            return YES;
        }
        return NO;
    }

#20


1  

The best way in any case is to check the length of the given string.For this if your string is myString then the code is:

在任何情况下,最好的方法是检查给定字符串的长度。为此,如果您的字符串是myString,那么代码是:

    int len = [myString length];
    if(len == 0){
       NSLog(@"String is empty");
    }
    else{
      NSLog(@"String is : %@", myString);
    }

#21


1  

if (string.length == 0) stringIsEmpty;

#22


1  

check this :

检查:

if ([yourString isEqualToString:@""])
{
    NsLog(@"Blank String");
}

Or

if ([yourString length] == 0)
{
    NsLog(@"Blank String");
}

Hope this will help.

希望这将帮助。

#23


1  

You can easily check if string is empty with this:

您可以使用以下工具轻松检查字符串是否为空:

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

#24


1  

I have checked an empty string using below code :

我用下面的代码检查了一个空字符串:

//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"];  
}

#25


1  

Its as simple as if([myString isEqual:@""]) or if([myString isEqualToString:@""])

它就像([myString isEqual:@"])或if([myString isEqualToString:@"]一样简单。

#26


1  

//Different validations:
 NSString * inputStr = @"Hey ";

//Check length
[inputStr length]

//Coming from server, check if its NSNull
[inputStr isEqual:[NSNull null]] ? nil : inputStr

//For validation in allowed character set
-(BOOL)validateString:(NSString*)inputStr
{
    BOOL isValid = NO;
    if(!([inputStr length]>0))
    {
        return isValid;

    }

    NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet characterSetWithCharactersInString:@".-"];
    [allowedSet formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet]];
    if ([inputStr rangeOfCharacterFromSet:[allowedSet invertedSet]].location == NSNotFound)
    {
        // contains only decimal set and '-' and '.'

    }
    else
    {
        // invalid
        isValid = NO;

    }
    return isValid;
}

#27


0  

if(str.length == 0 || [str isKindOfClass: [NSNull class]]){
    NSLog(@"String is empty");
}
else{
    NSLog(@"String is not empty");
}    

#28


0  

You can have an empty string in two ways:

你可以用两种方法得到一个空字符串:

1) @"" // Does not contain space

1) @“”//不包含空格

2) @" " // Contain Space

2) @“”//包含空格

Technically both the strings are empty. We can write both the things just by using ONE Condition

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

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

#29


-1  

if( [txtMobile.text length] == 0 )
{
    [Utility showAlertWithTitleAndMessage: AMLocalizedString(@"Invalid Mobile No",nil) message: AMLocalizedString(@"Enter valid Mobile Number",nil)];
}

#1


1082  

You can check if [string length] == 0. This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length on nil will also return 0.

您可以检查[string length]是否= 0。这将检查它是否是一个有效的空字符串(@""),如果它是nil,因为在nil上调用length也会返回0。

#2


126  

Marc's answer is correct. But I'll take this opportunity to include a pointer to Wil Shipley's generalized isEmpty, which he shared on his blog:

马克的回答是正确的。但是,我想借此机会介绍一下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);
}

#3


92  

The first approach is valid, but doesn't work if your string has blank spaces (@" "). So you must clear this white spaces before testing it.

第一种方法是有效的,但是如果您的字符串有空格(@“”),则不能使用。因此,在测试之前,您必须清除这些空白。

This code clear all the blank spaces on both sides of the string:

此代码清除字符串两边的所有空格:

[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];

One good idea is create one macro, so you don't have to type this monster line:

一个好主意是创建一个宏,所以你不必输入这个怪物行:

#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]

Now you can use:

现在您可以使用:

NSString *emptyString = @"   ";

if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");

#4


30  

One of the best solution I ever seen (better than Matt G's one) is this improved inline function I picked up on some Git Hub repo (Wil Shipley's one, but I can't find the link) :

我所见过的最好的解决方案之一(比Matt G的更好)是我在Git Hub repo上获得的这个改进的内联函数(Wil Shipley的那个,但我找不到链接):

// Check if the "thing" pass'd is empty
static inline BOOL isEmpty(id thing) {
    return thing == nil
    || [thing isKindOfClass:[NSNull class]]
    || ([thing respondsToSelector:@selector(length)]
        && [(NSData *)thing length] == 0)
    || ([thing respondsToSelector:@selector(count)]
        && [(NSArray *)thing count] == 0);
}

#5


14  

You should better use this category:

你最好使用这个类别:

@implementation NSString (Empty)

    - (BOOL) isWhitespace{
        return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);
    }

@end

#6


12  

Just pass your string to following method:

只需将字符串传递给以下方法:

+(BOOL)isEmpty:(NSString *)str
{
    if(str.length==0 || [str isKindOfClass:[NSNull class]] || [str isEqualToString:@""]||[str  isEqualToString:NULL]||[str isEqualToString:@"(null)"]||str==nil || [str isEqualToString:@"<null>"]){
        return YES;
    }
    return NO;
}

#7


11  

I put this:

我把这个:

@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

The problem is that if self is nil, this function is never called. It'll return false, which is desired.

问题是如果self是nil,这个函数就不会被调用。它会返回false。

#8


9  

Another option is to check if it is equal to @"" with isEqualToString: like so:

另一个选项是用isEqualToString检查它是否等于@":like so:

if ([myString isEqualToString:@""]) {
    NSLog(@"myString IS empty!");
} else {
    NSLog(@"myString IS NOT empty, it is: %@", myString);
}

#9


5  

Just use one of the if else conditions as shown below:

使用if else条件,如下所示:

Method 1:

方法1:

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

Method 2:

方法2:

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

#10


5  

Swift Version

Even though this is an Objective C question, I needed to use NSString in Swift so I will also include an answer here.

尽管这是一个客观的C问题,但我需要在Swift中使用NSString,因此我将在这里包含一个答案。

let myNSString: NSString = ""

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

Or if NSString is an Optional:

或者如果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.")
    }
}

The normal Swift String version is

普通的Swift字符串版本是

let myString: String = ""

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

See also: Check empty string in Swift?

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

#11


5  

May be this answer is the duplicate of already given answers, but i did few modification and changes in the order of checking the conditions. Please refer the below code:

可能这个答案是已经给出答案的重复,但是我在检查条件的顺序上做了一些修改和修改。请参考以下代码:

+(BOOL)isStringEmpty:(NSString *)str
    {
        if(str == nil || [str isKindOfClass:[NSNull class]] || str.length==0) {
            return YES;
       }
        return NO;
    }

#12


4  

You can check either your string is empty or not my using this method:

你可以用这个方法检查你的字符串是否为空:

+(BOOL) isEmptyString : (NSString *)string
{
    if([string length] == 0 || [string isKindOfClass:[NSNull class]] || 
       [string isEqualToString:@""]||[string  isEqualToString:NULL]  ||
       string == nil)
     {
        return YES;         //IF String Is An Empty String
     }
    return NO;
}

Best practice is to make a shared class say UtilityClass and ad this method so that you would be able to use this method by just calling it through out your application.

最佳实践是创建一个共享类,比如实用类和这个方法,这样您就可以通过调用应用程序来使用这个方法。

#13


4  

You have 2 methods to check whether the string is empty or not:

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

Let's suppose your string name is NSString *strIsEmpty.

假设您的字符串名称是NSString *strIsEmpty。

Method 1:

方法1:

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

else
{
    //String is not empty
}

Method 2:

方法2:

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

else
{
    //String is not empty
}

Choose any of the above method and get to know whether string is empty or not.

选择上面的任何一个方法,并了解字符串是否为空。

#14


3  

Very useful post, to add NSDictionary support as well one small change

非常有用的贴子,添加NSDictionary支持以及一个小改变

static inline BOOL isEmpty(id thing) {
    return thing == nil
    || [thing isKindOfClass:[NSNull class]]
    || ([thing respondsToSelector:@selector(length)]
        && ![thing respondsToSelector:@selector(count)]
        && [(NSData *)thing length] == 0)
    || ([thing respondsToSelector:@selector(count)]
        && [thing count] == 0);
}

#15


3  

Simply Check your string length

只需检查字符串长度

 if (!yourString.length)
 {
   //your code  
 }

a message to NIL will return nil or 0, so no need to test for nil :).

发送到NIL的消息将返回NIL或0,因此不需要测试NIL:)。

Happy coding ...

快乐的编码…

#16


2  

It is working as charm for me

它对我很有吸引力

If the NSString is s

如果NSString是s

if ([s isKindOfClass:[NSNull class]] || s == nil || [s isEqualToString:@""]) {

    NSLog(@"s is empty");

} else {

    NSLog(@"s containing %@", s);

}

#17


2  

So aside from the basic concept of checking for a string length less than 1, it is important to consider context deeply. Languages human or computer or otherwise might have different definitions of empty strings and within those same languages, additional context may further change the meaning.

因此,除了检查小于1的字符串长度的基本概念之外,深入考虑上下文是很重要的。语言、人或计算机或其他可能对空字符串有不同的定义,在相同的语言中,附加的上下文可能会进一步改变其含义。

Let's say empty string means "a string which does not contain any characters significant in the current context".

假设空字符串表示“不包含当前上下文中任何重要字符的字符串”。

This could mean visually, as in color and background color are same in an attributed string. Effectively empty.

这可能意味着在视觉上,就像颜色和背景颜色在带属性字符串中是一样的。有效的空。

This could mean empty of meaningful characters. All dots or all dashes or all underscores might be considered empty. Further, empty of meaningful significant characters could mean a string that has no characters the reader understands. They could be characters in a language or characterSet defined as meaningless to the reader. We could define it a little differently to say the string forms no known words in a given language.

这可能意味着没有有意义的字符。所有的点或所有的破折号或所有的下划线可能被认为是空的。此外,没有意义的重要字符可能意味着没有读者理解的字符的字符串。它们可以是语言中的字符或被定义为对读者没有意义的字符集。我们可以用一种不同的方式来定义这个字符串在给定的语言中不存在已知的单词。

We could say empty is a function of the percentage of negative space in the glyphs rendered.

我们可以说,空是所渲染的符号中负空间百分比的函数。

Even a sequence of non printable characters with no general visual representation is not truly empty. Control characters come to mind. Especially the low ASCII range (I'm surprised nobody mentioned those as they hose lots of systems and are not whitespace as they normally have no glyphs and no visual metrics). Yet the string length is not zero.

即使是不具有一般视觉表示的不可打印字符序列也不是真正的空。我想到了控制角色。特别是低ASCII范围(我很惊讶没有人提到它们,因为它们连接了很多系统,而且不是空白,因为它们通常没有符号和视觉度量)。但是字符串长度不是0。

Conclusion. Length alone is not the only measure here. Contextual set membership is also pretty important.

结论。长度本身并不是唯一的衡量标准。上下文集成员关系也很重要。

Character Set membership is a very important common additional measure. Meaningful sequences are also a fairly common one. ( think SETI or crypto or captchas ) Additional more abstract context sets also exist.

字符集隶属度是一种非常重要的常用附加度量。有意义的序列也是相当常见的。(想想SETI或crypto或captchas)还有更多的抽象上下文集。

So think carefully before assuming a string is only empty based on length or whitespace.

因此,在假设字符串仅为空时,请仔细考虑。

#18


2  

- (BOOL)isEmpty:(NSString *)string{
    if ((NSNull *) string == [NSNull null]) {
        return YES;
    }
    if (string == nil) {
        return YES;
    }
    if ([string length] == 0) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
        return YES;
    }
    if([[string stringByStrippingWhitespace] isEqualToString:@""]){
        return YES;
    }
    return NO;
}

#19


2  

The best way is to use the category.
You can check the following function. Which has all the conditions to check.

最好的方法是使用这个类别。您可以检查以下函数。它有所有的条件去检查。

-(BOOL)isNullString:(NSString *)aStr{
        if([(NSNull *)aStr isKindOfClass:[NSNull class]]){
            return YES;
        }
        if ((NSNull *)aStr  == [NSNull null]) {
            return YES;
        }
        if ([aStr isKindOfClass:[NSNull class]]){
            return YES;
        }
        if(![[aStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]){
            return YES;
        }
        return NO;
    }

#20


1  

The best way in any case is to check the length of the given string.For this if your string is myString then the code is:

在任何情况下,最好的方法是检查给定字符串的长度。为此,如果您的字符串是myString,那么代码是:

    int len = [myString length];
    if(len == 0){
       NSLog(@"String is empty");
    }
    else{
      NSLog(@"String is : %@", myString);
    }

#21


1  

if (string.length == 0) stringIsEmpty;

#22


1  

check this :

检查:

if ([yourString isEqualToString:@""])
{
    NsLog(@"Blank String");
}

Or

if ([yourString length] == 0)
{
    NsLog(@"Blank String");
}

Hope this will help.

希望这将帮助。

#23


1  

You can easily check if string is empty with this:

您可以使用以下工具轻松检查字符串是否为空:

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

#24


1  

I have checked an empty string using below code :

我用下面的代码检查了一个空字符串:

//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"];  
}

#25


1  

Its as simple as if([myString isEqual:@""]) or if([myString isEqualToString:@""])

它就像([myString isEqual:@"])或if([myString isEqualToString:@"]一样简单。

#26


1  

//Different validations:
 NSString * inputStr = @"Hey ";

//Check length
[inputStr length]

//Coming from server, check if its NSNull
[inputStr isEqual:[NSNull null]] ? nil : inputStr

//For validation in allowed character set
-(BOOL)validateString:(NSString*)inputStr
{
    BOOL isValid = NO;
    if(!([inputStr length]>0))
    {
        return isValid;

    }

    NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet characterSetWithCharactersInString:@".-"];
    [allowedSet formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet]];
    if ([inputStr rangeOfCharacterFromSet:[allowedSet invertedSet]].location == NSNotFound)
    {
        // contains only decimal set and '-' and '.'

    }
    else
    {
        // invalid
        isValid = NO;

    }
    return isValid;
}

#27


0  

if(str.length == 0 || [str isKindOfClass: [NSNull class]]){
    NSLog(@"String is empty");
}
else{
    NSLog(@"String is not empty");
}    

#28


0  

You can have an empty string in two ways:

你可以用两种方法得到一个空字符串:

1) @"" // Does not contain space

1) @“”//不包含空格

2) @" " // Contain Space

2) @“”//包含空格

Technically both the strings are empty. We can write both the things just by using ONE Condition

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

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

#29


-1  

if( [txtMobile.text length] == 0 )
{
    [Utility showAlertWithTitleAndMessage: AMLocalizedString(@"Invalid Mobile No",nil) message: AMLocalizedString(@"Enter valid Mobile Number",nil)];
}