Check for an empty string
I have a little question. Seems easy but I don't get it worki开发者_StackOverflow社区ng. All I want is check if a string is empty or not. Here's what I have so far:
if(mystring.text != @""){
myPath = [myPath stringByAppendingString:mystring.text];
}
To compare an NSString
to another one, you would use isEqualToString
. You're checking for inequality, so it would be:
NSString *text = ...;
if (![text isEqualToString:@""]) {
...
}
But really, since you're just checking if the string is empty, you'll want something like
NSString *text = ...;
if ([text length] != 0) {
...
}
Note that if text
is nil
, the code in the if
-statement will not execute. This is because [nil length]
will return 0
. For more information about that, see "Sending Messages to nil" in Apple's documentation.
I suspect mystring.text
is an NSString
in your case, so it would be
if ([mystring.text length] != 0) {
myPath = [myPath stringByAppendingString:mystring.text];
}
you can try below few lines of code:
NSString *trimedString = [someString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if(trimedstr != [NSNull null]&& ![trimedstr isEqualToString:@""])
{
if([trimedstr length]>0)
{
NSLog(@"%@", trimedstr);
}
else
NSLog(@"%@",@"this is empty string");
}
I usually check if the length is > 0 for a positive test case, which also handles if nil.
something like: if ([someString length] > 0) { // do something with someString }
I'd use something like:
if(someString && [someString lenght])
// string is not empty
精彩评论