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.
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).
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.
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:@""] .
NSCharacterSet *charSet = [NSCharacterSet whitespaceCharacterSet];
NSString *trimmedString = [myString stringByTrimmingCharactersInSet:charSet];
if ([trimmedString isEqualToString:@""]) {
// it's empty or contains only white spaces
}
[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length > 0
Use this to test if the string contains characters other than whitespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With