开发者

Verify the existence of a word in an NSString

开发者 https://www.devze.com 2022-12-09 05:58 出处:网络
I searched a bit, but couldn\'t find an answer to this (probably very simple) question. I have an NSString, and I\'d like to check if it contains a word. Something like this:

I searched a bit, but couldn't find an answer to this (probably very simple) question.

I have an NSString, and I'd like to check if it contains a word. Something like this:

NSString *sentence = @"The quick brown fox";
NSString *word = @"quack";
if ([sentence containsWord:word]) {
    NSLog(@"Yes it does c开发者_开发知识库ontain that word");
}

Thanks.


The following should work:

NSString *sentence = @"The quick brown fox";
NSString *word = @"quack";
if ([sentence rangeOfString:word].location != NSNotFound) {
    NSLog(@"Yes it does contain that word");
}

It uses rangeOfString: to return an NSRange structure, indicating the location of the word, if it can't find it NSRange.location will be equal to NSNotFound.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号