Can NSRange determine if a snippet of text exists

2019-07-24 14:08发布

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!

2条回答
Rolldiameter
2楼-- · 2019-07-24 14:31

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.

查看更多
Deceive 欺骗
3楼-- · 2019-07-24 14:42

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
查看更多
登录 后发表回答