Objective c NSRange能否确定较大字符串中是否存在文本片段?

Objective c NSRange能否确定较大字符串中是否存在文本片段?,objective-c,nsrange,Objective C,Nsrange,我有一个从http GET返回的大字符串,我正在尝试确定它是否有特定的文本片段(请原谅我的错误) 我的问题是:我是否可以/应该使用NSRange确定此文本片段是否存在 NSRange textRange; textRange =[[responseString lowercaseString] rangeOfString:[@"hat" lowercaseString]]; if(textRange.location != NSNotFound) { //do some

我有一个从http GET返回的大字符串,我正在尝试确定它是否有特定的文本片段(请原谅我的错误)

我的问题是:我是否可以/应该使用NSRange确定此文本片段是否存在

  NSRange textRange;
  textRange =[[responseString lowercaseString] rangeOfString:[@"hat" lowercaseString]];

  if(textRange.location != NSNotFound)
  {
    //do something magical with this hat
  }

提前谢谢你

您可以检查位置是否为
NSNotFound

NSRange textRange = [[responseString lowercaseString] rangeOfString:@"hat"];
if (textRange.location == NSNotFound) {
    // "hat" is not in the string
}
如果未找到字符串,
rangeOfString:
返回
{NSNotFound,0}

如果您经常使用它,您可以将其捆绑到
NSString
上的一个类别中:

@interface NSString (Helper)
- (BOOL)containsString:(NSString *)s;
@end

@implementation NSString (Helper)

- (BOOL)containsString:(NSString *)s
{
    return [self rangeOfString:s].location != NSNotFound;
}

@end

iOS 9.2、Xcode 7.2、ARC启用

感谢“mipadi”的原创贡献。我想详细说明并更新答案

你为什么还要使用这种技术?嗯,
-(BOOL)containssString:(NSString*)str
仅受iOS 8.0及更高版本的支持

我最喜欢的用法是:

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;
}
希望这对别人有帮助!干杯