-5

如何删除两个字符串中的常用字母并使用剩余的唯一字母生成新字符串?

例如:

String 1= Optimus Prime,
String 2= Deja Thoras,

新字符串应该是:Djaha

4

2 回答 2

5

只需枚举字符串中的字符并删除匹配范围。一定要搜索“无大小写”(即大小写字母之间的区别无关紧要)。下面的代码片段记录了“Djaha”,正如开篇所期望的那样。

NSString *firstString = @"Deja Thoras";
NSString *secondString = @"Optimus Prime";

NSMutableString *outputString = [NSMutableString stringWithString:firstString];

[outputString enumerateSubstringsInRange:NSMakeRange(0, firstString.length) options:NSStringEnumerationByComposedCharacterSequences 
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
    if ([secondString rangeOfString:substring options:NSCaseInsensitiveSearch].location != NSNotFound) {
        [outputString deleteCharactersInRange:substringRange];
    }
}];

NSLog(@"%@", outputString);

如果这是一个常见的操作,我会将代码放入一个类别中,方法名称如下stringByRemovingMatchingCharactersInString:

于 2013-07-02T09:46:38.197 回答
5

这是一种避免字符枚举细节的方法:

NSString *string1 = @"Deja Thoras";
NSString *string2 = @"Optimus Prime";

NSCharacterSet *filterSet = [NSCharacterSet characterSetWithCharactersInString:string2];
NSString *filteredString = [[string1 componentsSeparatedByCharactersInSet:filterSet] componentsJoinedByString:@""];
于 2013-07-02T09:34:17.263 回答