cyclingIsBetter
cyclingIsBetter

Reputation: 17591

IOS: verify if a string is an empty string

is there a method to verify if a NSString haven't characters? example of string without characters can be:

@"" or @" " or @"\n " or @"\n\n ", I want cosider these strings as empty strings and print a nslog that say me that these are emty, what kind of control I should use?

Upvotes: 5

Views: 636

Answers (2)

WendiKidd
WendiKidd

Reputation: 4373

You can iterate through every character in the string and check if it is the space (" ") or newline ("\n") character. If not, return false. Else if you search through the whole string and didn't return false, it is "empty".

Something like this:

NSString* myStr = @"A STRING";
for(int i = 0; i < [myStr length]; i++)
{
    if(!(([myStr characterAtIndex:i] == @' ') || ([myStr characterAtIndex:i] == @'\n')))
    {
        return false;
    }
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

You can use this test:

if ([[myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
    // The string is empty
}

Upvotes: 7

Related Questions