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 *)striOS 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 に答える