Can NSRange determine if a snippet of text exists in a larger string?

佐手、 提交于 2019-12-11 02:27:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!