Verify the existence of a word in an NSString

扶醉桌前 提交于 2019-12-10 21:44:08

问题


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 contain that word");
}

Thanks.


回答1:


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.



来源:https://stackoverflow.com/questions/1581916/verify-the-existence-of-a-word-in-an-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!