How do I check if a string contains another string in Objective
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?
NOTE: This answer is now obsolete
Create a category for NSString:
@interface NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring;
@end
// - - - -
@implementation NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring
{
NSRange range = [self rangeOfString : substring];
BOOL found = ( range.location != NSNotFound );
return found;
}
@end
EDIT: Observe Daniel Galasko's comment below regarding naming
Since this seems to be a high-ranking result in Google, I want to add this:
iOS 8 and OS X 10.10 add the containsString:
method to NSString
. An updated version of Dave DeLong's example for those systems:
NSString *string = @"hello bla bla";
if ([string containsString:@"bla"]) {
NSLog(@"string contains bla!");
} else {
NSLog(@"string does not contain bla");
}
链接地址: http://www.djcxy.com/p/2036.html
上一篇: 如何检查字符串是否包含子字符串?