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
NSString *string = @"hello bla bla";
ReplyDeleteif ([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".
Make a category on NSString:
ReplyDelete@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
I guess that's good enough. You may find this useful http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(string_functions).
ReplyDelete