2

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

我的问题是:我可以/应该使用 NSRange 来确定这段文本是否存在吗?

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

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

先感谢您!

4

2 回答 2

11

您可以检查位置是否为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
于 2011-01-17T17:13:08.860 回答
1

iOS 9.2、Xcode 7.2、ARC 已启用

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

为什么还要使用这种技术?嗯,- (BOOL)containsString:(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;
}

希望这对某人有帮助!干杯。

于 2016-01-23T02:16:06.367 回答