Reputation: 2024
I'm looking for a method that can extract the same words from NSStrings. This sounds confusing, but here's what I'm looking for:
String 1: @"Word 4"
String 2: @"Word 5"
-> Result: @"Word"
as NSString (since 4 and 5 are not the same, they are removed, and then the space because, well, it's useless)
This function also needs to strip out words instead of characters, so an input would result in something like this:
String 1: @"Word Abcdef"
String 2: @"Word Abcedf"
-> Result: @"Word"
instead of @"Word Abc"
-- OR --
String 1: @"Word 12"
String 2: @"Word 15"
-> Result: @"Word"
instead of @"Word 1"
Upvotes: 0
Views: 257
Reputation: 2024
I took both @Moszi and @Carters ideas and shortened the code for the most efficiency, and here's what I've found to work so far:
NSArray *words = [@"String 1" componentsSeparatedByString:@" "];
NSArray *words2 = [@"String 2" componentsSeparatedByString:@" "];
NSMutableString *title = [NSMutableString string];
for (NSInteger i = 0; i < [words count] && i < [words2 count]; i++) {
NSString *word = [words objectAtIndex:i];
NSString *word2 = [words2 objectAtIndex:i];
if ([word caseInsensitiveCompare:word2] == NSOrderedSame)
[title appendFormat:@"%@%@",(([title length]>0)?@" ":@""), word];
}
I made also made sure not to get an error when one string has more words than another.
Upvotes: 0
Reputation: 3093
Split the strings into an array of words and then iterate through the array to extract the similar words.
NSArray* firstStringComponents = [string1 componentsSeparatedByString:@" "];
NSArray* secondStringComponents = [string2 componentsSeparatedByString:@" "];
BOOL notAtEnd = true;
int i = 0;
NSMutableString* returnString = [[NSMutableString alloc] init];
while(notAtEnd)
{
NSString* one = [firstStringComponents objectAtIndex:i];
NSString* two = [secondStringComponents objectAtIndex:i];
if([one isEqualTo:two])
//append one to the returnString
i++;
notAtEnd = i < [firstStringComponents count] && i < [secondStringComponents count];
}
return returnString;
Upvotes: 0
Reputation: 3236
i would split both strings by white space characters like componentsSeparatedByString:, then use a loop to compare each word from one array to the other. if the word appears both arrays I would add it to an NSMutableArray, and at the end use componentsJoinedByString: to get your final string.
Hope this helps.
Upvotes: 1