views:

1833

answers:

2

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");
}

I typed that straight into stack so sorry if there are errors, but there would be if I was doing it in Xcode so you don't need to point any out.

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

+2  A: 

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

ahmadabdolkader
This is a great resource. Thanks!
Abel Martin
+12  A: 
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".

Dave DeLong
From OP: *"I typed that straight into stack so sorry if there are errors, but there would be if I was doing it in Xcode so you don't need to point any out."*
KennyTM
I kind of meant things like missing out letters and semi colons and such. but this answer helps because it's a little more "refined" (I think that's the correct word to use here)
Jonathan