Skip navigation.
 
mlRe: NSString and string contains
FROM : Chris Hanson
DATE : Mon Mar 03 05:45:19 2008

On Mar 2, 2008, at 12:31 PM, Tom Jones wrote:

> I have an NSArray which contains String values and I want to loop 
> though it and determine if any of those string contain words I'm 
> looking for. I have tried but have been unsuccessful.


Predicates are great for this.  They're a Foundation facility for 
performing queries on collections.

  - (NSArray *)itemsInCollection:(NSArray *)collection containingWord:
(NSString *)word {
      NSPredicate *containsWordPredicate = [NSPredicate @"SELF 
CONTAINS[cd] %@", word];

      return [collection 
filteredArrayUsingPredicate:containsWordPredicate];
  }

This will return a new collection containing all items in the passed-
in collection that themselvs contain the given word, and it will do 
the comparison in a case-insensitive and diacritic-insensitive 
fashion.  (Thus if word is @"resume" then @"résumé" and @"Resume" 
would be considered matches.)

In general, any time you can express something as a query rather than 
as explicit iteration, it's a win -- whether you're talking about 
Cocoa or any other framework.  This is because it lets the framework 
itself determine the best way to achieve the results, which can change 
over time.

  -- Chris

Related mailsAuthorDate
mlNSString and string contains Tom Jones Mar 2, 21:31
mlRe: NSString and string contains Seth Willits Mar 2, 22:39
mlRe: NSString and string contains Andrew Merenbach Mar 2, 22:44
mlRe: NSString and string contains j o a r Mar 2, 23:01
mlRe: NSString and string contains Johannes Huning Mar 2, 23:02
mlRe: NSString and string contains Andrew Merenbach Mar 2, 23:16
mlRe: NSString and string contains Chris Hanson Mar 3, 05:45
mlRe: NSString and string contains Jens Alfke Mar 3, 07:50