本文介绍了正在检测NSString是否包含...?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检测字符串是否包含某个单词?例如,我下面有一个字符串,其内容为:
How can I detect if a string contains a certain word? For example, I have a string below which reads:
@"Here is my string."
我想知道是否可以检测到字符串中的单词,例如"is".
I'd like to know if I can detect a word in the string, such as "is" for example.
推荐答案
这是我的处理方式:
NSString *someString = @"Here is my string";
NSRange isRange = [someString rangeOfString:@"is " options:NSCaseInsensitiveSearch];
if(isRange.location == 0) {
//found it...
} else {
NSRange isSpacedRange = [someString rangeOfString:@" is " options:NSCaseInsensitiveSearch];
if(isSpacedRange.location != NSNotFound) {
//found it...
}
}
您可以轻松地将其作为类别添加到NSString
:
You can easily add this as a category onto NSString
:
@interface NSString (JRStringAdditions)
- (BOOL)containsString:(NSString *)string;
- (BOOL)containsString:(NSString *)string
options:(NSStringCompareOptions)options;
@end
@implementation NSString (JRStringAdditions)
- (BOOL)containsString:(NSString *)string
options:(NSStringCompareOptions)options {
NSRange rng = [self rangeOfString:string options:options];
return rng.location != NSNotFound;
}
- (BOOL)containsString:(NSString *)string {
return [self containsString:string options:0];
}
@end
这篇关于正在检测NSString是否包含...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!