Nic Hubbard
Nic Hubbard

Reputation: 42139

NSString: Find parts of string in another string

I know how to find a string in another string, that is easy. But in this case I want to find John Smith within the allProfessors string. So I figured I could just split the string and search for both parts, which works how I want:

NSString *fullName = @"John Smith";
NSArray *parts = [fullName componentsSeparatedByString:@" "];
NSString *allProfessors = @"Smith, John; Clinton, Bill; Johnson, John";
NSRange range = [[allProfessors lowercaseString] rangeOfString:[[parts objectAtIndex:0] lowercaseString]];
NSRange range2 = [[allProfessors lowercaseString] rangeOfString:[[parts objectAtIndex:1] lowercaseString]];
if(range.location != NSNotFound && range2.location != NSNotFound) {
    NSLog(@"Found");
} else {
    NSLog(@"Not Found");
}

What I want to know is, is this the BEST way to do this or is there a more preferred method to do what I want?

In addition to this, what if my fullName is longer than my allProfessors name, such as:

NSString *fullName = @"Gregory Smith";
NSString *allProfessors = @"Smith, Greg; Clinton, Bill; Johnson, John";

I still want there to be a match for Greg Smith and Gregory Smith.

Upvotes: 1

Views: 1106

Answers (1)

Sam
Sam

Reputation: 27354

You could use regular expressions, which I prefer to use. See RegexKitLite.

With RegexKitLite, you could use a regular expression like (untested):

NSString *regEx = @"(?i)Smith,\\s*\\w";
NSArray *matchingStrings = [allProfessors componentsMatchedByRegex:regEx];

if ([matchingStrings count] == 0)  // not found!
{
   [...]
}
else
{
   [...]
}

Using RegexKitLite you could alternatively have used [NSString stringByMatching:(NSString*)].

You can really do a lot with regular expression. There are a ton of different functions available through Using RegexKitLite. The regular expression above should find people with the last name of Smith.

Regular Expression explained:

  • (?i) make this case insensitive
  • Smith matches last name of Smith. Obviously you could change this to anything
  • , match a comma
  • \\s* match any number of spaces (greedy)
  • \\w match a word

Also, you could use [NSString rangeOfString:options:] function like:

if ([myString rangeOfString:@"John" options:NSCaseInsensitiveSearch].location != NSNotFound &&
    [myString rangeOfString:@"Smith" options:NSCaseInsensitiveSearch].location != NSNotFound)
{
   NSLog(@"Found");
}
else
{
   NSLog(@"Not Found");
}

Also see similar functions like [rangeOfString:options:range:locale:] so that you can do case insensitive searches and even specify a locale.

Upvotes: 2

Related Questions