2011-11-23 55 views
0

我正在寻找一种可以从NSString中提取相同单词的方法。这听起来有点混乱,但这里是我在寻找:在NSStrings中获取类似的字符

串1:@"Word 4"
字符串2:@"Word 5"
- >结果:@"Word"作为的NSString(因为4,5是不一样的,他们被删除,然后将空间,因为,它是无用的)

此功能也需要去掉词语而不是字符,所以输入将导致这样的事情:

字符串1:@"Word Abcdef"
字符串2:>结果 -
:的@"Word"代替@"Word Abc"
- 或 -
字符串1:@"Word 12"
字符串2:@"Word 15"
- >结果:@"Word 1"

+0

关于你所能做的就是解析成单个单词('componentsSeparatedBy ...'),然后对这些单词进行排序/比较。 –

回答

0

我拿了两个@Moszi和@Carters思路和缩短为最高效的代码,这里就是我发现工作至今:

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)[email protected]" ":@""), word]; 
} 

我做了也做不肯定当一个字符串比另一个字词多时得到错误。

1

@"Word"代替我将通过分割两个串像componentsSeparatedByString:这样的空白字符,然后使用循环来比较一个数组中的每个单词到另一个数组。如果单词出现在两个数组中,我会将它添加到一个NSMutableArray中,并在最后使用componentsJoinedByString:来获得最终的字符串。

希望这会有所帮助。

0

将字符串拆分为单词数组,然后遍历数组以提取相似的单词。

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;