Jak sprawdzić, czy łańcuch znaków jest pusty w Objective C?

Jak sprawdzić, czy NSString jest pusty w Objective C?

Author: Meet Doshi, 2009-05-22

30 answers

Możesz sprawdzić, czy [string length] == 0. To sprawdzi, czy jest to poprawny, ale pusty łańcuch ( @ "" ), jak również czy jest to nil, ponieważ wywołanie {[1] } na nil zwróci również 0.

 1096
Author: Marc Charbonneau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-28 15:17:27

Odpowiedź marca jest prawidłowa. Ale skorzystam z okazji, aby dołączyć wskaźnik do uogólnionego isEmpty Wila Shipleya, który podzielił się na swoim blogu :

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);
}
 126
Author: Matt G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-08 23:36:24

Pierwsze podejście jest poprawne, ale nie działa, jeśli łańcuch znaków ma spacje (@" "). Musisz więc wyczyścić te białe spacje przed testowaniem.

Ten kod usuwa wszystkie puste spacje po obu stronach łańcucha:

[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];

Dobrym pomysłem jest stworzenie jednego makra, więc nie musisz wpisywać tej linii potwora:

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

Teraz możesz użyć:

NSString *emptyString = @"   ";

if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");
 93
Author: SEQOY Development Team,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-20 20:49:34

Jednym z najlepszych rozwiązań jakie kiedykolwiek widziałem (lepsze od Matta G) jest ta ulepszona funkcja inline, którą podłapałem na jakimś Git Hub repo (Wil Shipley ' s one, ale nie mogę znaleźć linku):

// 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);
}
 30
Author: Rob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-08 05:12:38

Powinieneś lepiej użyć tej kategorii:

@implementation NSString (Empty)

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

@end
 15
Author: Cœur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-12 05:22:13

Po prostu Przekaż swój łańcuch do następującej metody:

+(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;
}
 12
Author: Mani Vannan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-25 13:16:48

Dodałem to:

@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

Problem polega na tym, że jeśli self jest zerowy, funkcja ta nigdy nie jest wywoływana. Zwróci false, co jest pożądane.

 11
Author: J. Chang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-02 07:53:02

Inną opcją jest sprawdzenie, czy jest ona równa @"" z isEqualToString: w ten sposób:

if ([myString isEqualToString:@""]) {
    NSLog(@"myString IS empty!");
} else {
    NSLog(@"myString IS NOT empty, it is: %@", myString);
}
 9
Author: chown,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-27 03:45:48

Wystarczy użyć jednego z if else warunki jak pokazano poniżej:

Metoda 1:

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

Metoda 2:

if ([yourString length] == 0) {
    // Empty yourString
} else {
    // yourString is not empty
}
 5
Author: Samir Jwarchan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-02 09:55:38

Wersja Swift

Mimo że jest to pytanie Objective C, musiałem użyć NSString w języku Swift, więc dołączę tutaj również odpowiedź.

let myNSString: NSString = ""

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

Lub jeśli NSString jest Opcjonalne:

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.")
    }
}

Normalna wersja Swift String to

let myString: String = ""

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

Zobacz także: Sprawdź pusty łańcuch w Swift?

 5
Author: Suragch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:18:23

Być może ta odpowiedź jest duplikatem już udzielonych odpowiedzi, ale zrobiłem kilka modyfikacji i zmian w kolejności sprawdzania warunków. Proszę zapoznać się z poniższym kodem:

+(BOOL)isStringEmpty:(NSString *)str
    {
        if(str == nil || [str isKindOfClass:[NSNull class]] || str.length==0) {
            return YES;
       }
        return NO;
    }
 5
Author: iDevAmit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-16 08:09:05

Możesz sprawdzić, czy twój ciąg jest pusty lub nie mój za pomocą tej metody:

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

Najlepszą praktyką jest, aby udostępniona Klasa mówiła UtilityClass i reklamowała tę metodę, abyś mógł użyć tej metody po prostu wywołując ją przez swoją aplikację.

 4
Author: Fatima Arshad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-24 18:12:03

Masz 2 metody, aby sprawdzić, czy łańcuch jest pusty, czy nie:

Załóżmy, że Twoja nazwa łańcucha to NSString *strIsEmpty.

Metoda 1:

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

else
{
    //String is not empty
}

Metoda 2:

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

else
{
    //String is not empty
}

Wybierz dowolną z powyższych metod i dowiedz się, czy string jest pusty czy nie.

 4
Author: Aditya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-30 14:45:06

Bardzo przydatny post, aby dodać wsparcie NSDictionary, a także jedną małą zmianę

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);
}
 3
Author: Zeev Vax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-02 02:09:40

Po prostu sprawdź długość łańcucha

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

Wiadomość do NIL zwróci nil lub 0, więc nie ma potrzeby testowania na nil :).

Szczęśliwego kodowania ...
 3
Author: Aks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-20 18:25:16

To działa jak urok dla mnie

Jeśli NSString jest s

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

    NSLog(@"s is empty");

} else {

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

}
 2
Author: Salim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-30 11:33:53

Tak więc oprócz podstawowej koncepcji sprawdzania długości łańcucha poniżej 1, ważne jest, aby wziąć pod uwagę kontekst głęboko. Języki ludzkie, komputerowe lub inne mogą mieć różne definicje pustych ciągów i w tych samych językach dodatkowy kontekst może dodatkowo zmienić znaczenie.

Załóżmy, że pusty łańcuch oznacza "łańcuch, który nie zawiera żadnych znaków znaczących w bieżącym kontekście".

Może to oznaczać wizualnie, jak w kolorze i tle kolory są takie same w przypisanym ciągu. Skutecznie pusty.

Może to oznaczać brak znaczących znaków. Wszystkie kropki, myślniki lub podkreślenia mogą być uznane za puste. Co więcej, pusty znaczący znak może oznaczać ciąg znaków, który nie ma znaków, które czytelnik rozumie. Mogą to być znaki w języku lub zestawie znaków zdefiniowanym jako bez znaczenia dla czytelnika. Możemy zdefiniować to trochę inaczej, mówiąc, że ciągi znaków nie są znane słowa w danym język.

Możemy powiedzieć, że empty jest funkcją procentową przestrzeni ujemnej w wyrenderowanych glifach.

Nawet sekwencja znaków niedrukowalnych bez ogólnej reprezentacji wizualnej nie jest naprawdę pusta. Postacie sterujące przychodzą na myśl. Szczególnie niski zakres ASCII (dziwię się, że nikt o nich nie wspomniał, ponieważ podłączają wiele systemów i nie są białymi spacjami, ponieważ zwykle nie mają glifów ani metryk wizualnych). Jednak Długość łańcucha nie jest zerowa.

Wniosek. Sama długość nie jest tu jedyną miarą. Bardzo ważne jest również członkostwo w zestawach kontekstowych.

Skład zestawu znaków jest bardzo ważną, wspólną miarą dodatkową. Sekwencje znaczące są również dość powszechne. (think SETI or crypto or captchas ) Istnieją również dodatkowe, bardziej abstrakcyjne zbiory kontekstów.

Więc zastanów się dokładnie przed założeniem, że łańcuch jest pusty tylko na podstawie długości lub białych znaków.

 2
Author: uchuugaka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-25 14:06:07
- (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;
}
 2
Author: Ptbaileys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-30 06:35:38

Najlepszym sposobem jest użycie kategorii.
Możesz sprawdzić następującą funkcję. Który ma wszystkie warunki do sprawdzenia.

-(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;
    }
 2
Author: Tarun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-02 07:24:07

Najlepszym sposobem w każdym przypadku jest sprawdzenie długości danego ciągu.W tym przypadku, jeśli twój ciąg znaków jest mistring, to kod jest:

    int len = [myString length];
    if(len == 0){
       NSLog(@"String is empty");
    }
    else{
      NSLog(@"String is : %@", myString);
    }
 1
Author: AJS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-27 12:17:20
if (string.length == 0) stringIsEmpty;
 1
Author: Harish Nagisetty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-30 13:48:08

Sprawdź to:

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

Lub

if ([yourString length] == 0)
{
    NsLog(@"Blank String");
}
Mam nadzieję, że to pomoże.
 1
Author: Mayur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-25 13:20:13

Możesz łatwo sprawdzić, czy łańcuch jest pusty za pomocą tego:

if ([yourstring isEqualToString:@""]) {
    // execute your action here if string is empty
}
 1
Author: user3213914,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-12 21:43:12

Sprawdziłem pusty łańcuch używając poniższego kodu:

//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"];  
}
 1
Author: Jayprakash Dubey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-30 12:46:32

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

 1
Author: Ahsan Ebrahim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-30 10:39:05
//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;
}
 1
Author: Rohit Kashyap,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-02 16:25:25
if(str.length == 0 || [str isKindOfClass: [NSNull class]]){
    NSLog(@"String is empty");
}
else{
    NSLog(@"String is not empty");
}    
 0
Author: C_compnay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-30 06:45:27

Możesz mieć pusty łańcuch na dwa sposoby:

1) @"" // nie zawiera spacji

2) @" " // Contain Space

Technicznie oba łańcuchy są puste. Możemy napisać obie rzeczy po prostu używając jednego warunku

if ([firstNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""].length==0)
{
    NSLog(@"Empty String");
}
else
{
    NSLog(@"String contains some value");
}
 0
Author: Chetan Rajauria,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-02 10:31:35

Spróbuj wykonać następujące czynności

NSString *stringToCheck = @"";

if ([stringToCheck isEqualToString:@""])
{
   NSLog(@"String Empty");
}
else
{
   NSLog(@"String Not Empty");
}
 0
Author: Rich Allen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-21 08:54:10
if( [txtMobile.text length] == 0 )
{
    [Utility showAlertWithTitleAndMessage: AMLocalizedString(@"Invalid Mobile No",nil) message: AMLocalizedString(@"Enter valid Mobile Number",nil)];
}
 -1
Author: Mohsin Sabasara,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-30 06:36:18