Vins
Vins

Reputation: 1934

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!

Upvotes: 4

Views: 2817

Answers (2)

user1040049
user1040049

Reputation:

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.

Upvotes: 3

thundersteele
thundersteele

Reputation: 673

What happens if you add a space at the end of the search string, like so:

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

If the string from searchField.text already ends with a space, you would have to remove it.

This is not a perfect solution yet, for example you would not find the search string if it is at the end of a sentence. Instead what you could do is not adding the whitespace character, but instead look at the character after the hit and make sure that it is not a letter. For this, take a look at the class NSCharacterSet:

NSCharacterSet * letters = [NSCharacterSet letterCharacterSet];
if (![letters characterIsMember:[textString characterAtIndex:(range.location+searchString.length)]]) {
... 
}

Upvotes: 2

Related Questions