问题
I have a large string coming back from an http GET and I'm trying to determine if it has a specific snippet of text or not (please forgive my sins here)
My question is this: Can / Should I use NSRange to determine if this snippet of text does exist?
NSRange textRange;
textRange =[[responseString lowercaseString] rangeOfString:[@"hat" lowercaseString]];
if(textRange.location != NSNotFound)
{
//do something magical with this hat
}
Thank you in advance!
回答1:
You can check to see if the location is NSNotFound:
NSRange textRange = [[responseString lowercaseString] rangeOfString:@"hat"];
if (textRange.location == NSNotFound) {
// "hat" is not in the string
}
If a string is not found, rangeOfString: returns {NSNotFound, 0}.
You could bundle this up into a category on NSString if you use it a lot:
@interface NSString (Helper)
- (BOOL)containsString:(NSString *)s;
@end
@implementation NSString (Helper)
- (BOOL)containsString:(NSString *)s
{
return [self rangeOfString:s].location != NSNotFound;
}
@end
回答2:
iOS 9.2, Xcode 7.2, ARC enabled
Thanks "mipadi" for the original contribution. I wanted to elaborate and update the answer.
Why would you still use this technique? Well, - (BOOL)containsString:(NSString *)str is only supported iOS 8.0 and later.
My favorite use of this:
if (yourString)
{
//Check to make yourString is not nil, otherwise NSInvalidArgumentException is raised.
if (!([yourString rangeOfString:@"stringToSearchFor"].location == NSNotFound))
{
//The string "stringToSearchFor" was found in yourString, i.e. the result is NOT NSNotFound.
}
else
{
//The string "stringToSearchFor" was not found in yourString.
}
}
else
{
nil;
}
Hope this helps someone! Cheers.
来源:https://stackoverflow.com/questions/4715830/can-nsrange-determine-if-a-snippet-of-text-exists-in-a-larger-string