How do I check if a string contains another string in Objective-C?

前端 未结 23 2013

How can I check if a string (NSString) contains another smaller string?

I was hoping for something like:

NSString *string = @\"hello bla         


        
23条回答
  •  春和景丽
    2020-11-22 15:06

    So personally I really hate NSNotFound but understand its necessity.

    But some people may not understand the complexities of comparing against NSNotFound

    For example, this code:

    - (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
        if([string rangeOfString:otherString].location != NSNotFound)
            return YES;
        else
            return NO;
    }
    

    has its problems:

    1) Obviously if otherString = nil this code will crash. a simple test would be:

    NSLog(@"does string contain string - %@", [self doesString:@"hey" containString:nil] ? @"YES": @"NO");
    

    results in !! CRASH !!

    2) What is not so obvious to someone new to objective-c is that the same code will NOT crash when string = nil. For example, this code:

    NSLog(@"does string contain string - %@", [self doesString:nil containString:@"hey"] ? @"YES": @"NO");
    

    and this code:

    NSLog(@"does string contain string - %@", [self doesString:nil containString:nil] ? @"YES": @"NO");
    

    will both result in

    does string contains string - YES
    

    Which is clearly NOT what you want.

    So the better solution that I believe works is to use the fact that rangeOfString returns the length of 0 so then a better more reliable code is this:

    - (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
        if(otherString && [string rangeOfString:otherString].length)
            return YES;
        else
            return NO;
    }
    

    OR SIMPLY:

    - (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
        return (otherString && [string rangeOfString:otherString].length);
    }
    

    which will for cases 1 and 2 will return

    does string contains string - NO
    

    That's my 2 cents ;-)

    Please check out my Gist for more helpful code.

提交回复
热议问题