Search code examples
objective-cxcodensstringnsrange

Search exact word in NSString


I need to find a word or several words. With this method, however, I find also piece of word.

NSString *searchString = [NSString stringWithFormat:@"%@",searchField.text];
NSRange range = [textString rangeOfString : searchString];

    if (range.location != NSNotFound) {


        NSLog(@"textString = %@", textString);

    }

I need the word / words exact

How can I do?

Thank you!


Solution

  • There are various ways of parsing/finding sub-strings in NSString:

    • NSString itself
    • NSRegularExpression. This would probably better suit your needs since you can tackle the scenario of surrounding white-spaces around words. Thus is won't return the cat from catapult when searching for cat.
    • NSScanner (most likely overkill for you needs)

    ... and they, of course, each have their PROs and CONs.

    NSString has 9 methods grouped under "Finding Characters and Substrings". Methods such as:

    -rangeOfString:
    Finds and returns the range of the first occurrence of a given string within the receiver.

    NSRegularExpression has 5 methods grouped under "Searching Strings Using Regular Expressions". Methods such as:

    -numberOfMatchesInString: options: range:
    Returns the number of matches of the regular expression within the specified range of the string.

    It might also be useful to know about NSScanner, but this class would be more useful if you're parsing the string than simply looking for sub-parts.