简体   繁体   English

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

[英]How do I test if a string is empty in Objective-C?

How do I test if an NSString is empty in Objective-C?如何测试 Objective-C 中的NSString是否为空?

You can check if [string length] == 0 .您可以检查是否[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.这将检查它是否是一个有效但为空的字符串 (@"") 以及它是否为 nil,因为在 nil 上调用length也将返回 0。

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);
}

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!");

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 存储库(Wil Shipley 的一个,但我找不到链接)上找到的改进的内联函数:

// Check if the "thing" passed 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);
}

You should better use this category:你最好使用这个类别:

@implementation NSString (Empty)

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

@end

Another option is to check if it is equal to @"" with isEqualToString: like so:另一种选择是使用isEqualToString:检查它是否等于@"" isEqualToString:像这样:

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

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.问题是如果 self 为零,则永远不会调用此函数。 It'll return false, which is desired.它会返回 false,这是我们想要的。

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;
}

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;
  }

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.尽管这是一个 Objective 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 String版本是

let myString: String = ""

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

See also: Check empty string in Swift?另请参阅:在 Swift 中检查空字符串?

Just use one of the if else conditions as shown below:只需使用if else条件之一,如下所示:

Method 1:方法一:

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

Method 2:方法二:

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

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.最佳实践是将共享类称为 UtilityClass 并添加此方法,以便您只需在整个应用程序中调用它即可使用此方法。

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:方法一:

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

else
{
    //String is not empty
}

Method 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.选择上述任何一种方法并了解字符串是否为空。

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 ...快乐编码...

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);
}

It is working as charm for me它对我来说很有魅力

If the NSString is s如果NSStrings

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

    NSLog(@"s is empty");

} else {

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

}

So aside from the basic concept of checking for a string length less than 1, it is important to consider context deeply.因此,除了检查字符串长度小于 1 的基本概念之外,深入考虑上下文也很重要。 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.人类或计算机或其他语言可能对空字符串有不同的定义,并且在这些相同的语言中,额外的上下文可能会进一步改变含义。

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).尤其是低 ASCII 范围(我很惊讶没有人提到这些,因为它们包含大量系统并且不是空白,因为它们通常没有字形和视觉指标)。 Yet the string length is not zero.然而字符串长度不为零。

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 或加密或验证码)还存在其他更抽象的上下文集。

So think carefully before assuming a string is only empty based on length or whitespace.因此,在根据长度或空格假设字符串仅为空之前,请仔细考虑。

- (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;
}

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;
    }

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);
    }
if (string.length == 0) stringIsEmpty;

check this :检查这个:

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

Or要么

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

Hope this will help.希望这会有所帮助。

You can easily check if string is empty with this:您可以使用以下方法轻松检查字符串是否为空:

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

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

它就像if([myString isEqual:@""])if([myString isEqualToString:@""])

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

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我们可以通过使用ONE Condition 来写这两件事

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

Try the following尝试以下

NSString *stringToCheck = @"";

if ([stringToCheck isEqualToString:@""])
{
   NSLog(@"String Empty");
}
else
{
   NSLog(@"String Not Empty");
}

Based on multiple answers I have created a ready to use category combining @iDevAmit and @user238824 answers.基于多个答案,我创建了一个结合@iDevAmit 和@user238824 答案的即用型类别。

Specifically it goes in the following order具体按以下顺序进行

  1. Check for null/nil检查 null/nil
  2. Check if if string is empty using it's length count.使用它的长度计数检查字符串是否为空。
  3. Check if string is white spaces.检查字符串是否为空格。

Header Header

//
//  NSString+Empty.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSString (Empty)
- (BOOL)isEmptyOrWhiteSpacesOrNil;
@end

NS_ASSUME_NONNULL_END

Implementation执行

//
//  NSString+Empty.m

#import "NSString+Empty.h"

@implementation NSString (Empty)

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

- (BOOL)isEmptyOrWhiteSpacesOrNil {
     if(self == nil || [self isKindOfClass:[NSNull class]] || self.length==0 || [self isWhitespace] == YES) {
            return YES;
       }
      return NO;
  }

@end

/*
 Credits
 1. https://stackoverflow.com/a/24506942/7551807
 2. https://stackoverflow.com/a/1963273/7551807
 */

Usage: of-course the function will never be triggered if your string is null. Case one is there just for extra security.用法:当然,如果您的字符串是 null,则永远不会触发 function。第一种情况只是为了额外的安全性。 I advice checking for nullability before attempting to use this method.我建议在尝试使用此方法之前检查可空性。

if (myString) {
  if [myString isEmptyOrWhiteSpacesOrNil] {
     // String is empty
  }
} else {
// String is null
}
if(str.length == 0 || [str isKindOfClass: [NSNull class]]){
    NSLog(@"String is empty");
}
else{
    NSLog(@"String is not empty");
}    
if( [txtMobile.text length] == 0 )
{
    [Utility showAlertWithTitleAndMessage: AMLocalizedString(@"Invalid Mobile No",nil) message: AMLocalizedString(@"Enter valid Mobile Number",nil)];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM