Friday, June 1, 2012

String contains string in objective-c


How can I check if a string (NSString) contains another smaller string? I was hoping for something like:




NSString *string = @"hello bla bla";
NSLog(@"%d",[string containsSubstring:@"hello"]);



But the closest I could find was:




if ([string rangeOfString:@"hello"] == 0) {
NSLog(@"sub string doesnt exist");
} else {
NSLog(@"exists");
}



Anyway is that the best way to find if a string contains another string.


Source: Tips4all

3 comments:

  1. NSString *string = @"hello bla bla";
    if ([string rangeOfString:@"bla"].location == NSNotFound) {
    NSLog(@"string does not contain bla");
    } else {
    NSLog(@"string contains bla!");
    }


    The key is noticing that rangeOfString: returns an NSRange struct, and the documentation says that it returns the struct {NSNotFound, 0} if the "haystack" does not contain the "needle".

    ReplyDelete
  2. Make a category on NSString:

    @interface NSString ( containsCategory )
    - (BOOL) containsString: (NSString*) substring;
    @end

    // - - - -

    @implementation NSString ( containsCategory )

    - (BOOL) containsString: (NSString*) substring
    {
    NSRange range = [self rangeOfString : substring];
    BOOL found = ( range.location != NSNotFound );
    return found;
    }

    @end

    ReplyDelete
  3. I guess that's good enough. You may find this useful http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(string_functions).

    ReplyDelete