Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a NSString is empty or only contains whitespace or tabs? [duplicate]

I'm currently using isEqualToString:@"" and it works fine when the textField does have nothing. However, it does not catch the case when the input has only white spaces or tabs. What should I do to make it smarter so that input such as " " will not be allowed.

like image 290
OneZero Avatar asked Oct 24 '13 21:10

OneZero


People also ask

How do I know if Nsstring is empty?

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. There are some very rare NSStrings where this will result in a false negative (saying the string isn't empty, when, for practical purposes, it is).

How do I check if a string contains only whitespace?

To check if a string contains only spaces, call the trim() method on the string and check if the length of the result is equal to 0 . If the string has a length of 0 after calling the trim method, then the string contains only spaces.

How do I trim a string in Objective C?

stringByTrimmingCharactersInSet only removes characters from the beginning and the end of the string, not the ones in the middle. For those who are trying to remove space in the middle of a string, use [yourString stringByReplacingOccurrencesOfString:@" " withString:@""] .


2 Answers

NSCharacterSet *charSet = [NSCharacterSet whitespaceCharacterSet];
NSString *trimmedString = [myString stringByTrimmingCharactersInSet:charSet];
if ([trimmedString isEqualToString:@""]) {
    // it's empty or contains only white spaces
}
like image 125
DrummerB Avatar answered Oct 07 '22 10:10

DrummerB


[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length > 0

Use this to test if the string contains characters other than whitespace.

like image 25
Léo Natan Avatar answered Oct 07 '22 10:10

Léo Natan