gpt4 book ai didi

objective-c - NSRange 能否确定一段文本是否存在于较大的字符串中?

转载 作者:行者123 更新时间:2023-12-02 05:54:05 25 4
gpt4 key购买 nike

我有一个从 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

关于objective-c - NSRange 能否确定一段文本是否存在于较大的字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4715830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com