views:

109

answers:

2

Hi,

I am trying to find a word inside a phrase (NSString).

For this I've exploded the components of the phrase into individual substrings and now I am trying to compare them to the word I am looking for, but it doesn't work.

What would be the correct approach for this and fix for the software below?

NSString *myString = @"Mi Programa es genial";
NSArray *explodedDescription = [myString componentsSeparatedByString:@" "];

if ([explodedDescription objectAtIndex:1] == @"Programa" ) {
    NSLog(@"Found");
}
+7  A: 

NSStrings are compared with isEqualToString. You're comparing pointers instead of the values.

See NSString documentation

diciu
+2  A: 

You're doing it the hard way! Use NSString's -rangeOfString: method or one of its variants to get the location of a string in another string.

Preston
That won't work for *words*, since it will happily detect one word in another word. Naïve swear-filters are the most common victim; in that context, it's called the Scunthorpe problem (after a town in the UK whose name you can't say under a dumb swear-filter).
Peter Hosey
Obviously, you'd do word-boundary analysis for each result and continue the search if the result fails the check. See NSAttributedString's doubleClickAtIndex: method.
Preston