如何在iOS SDK中删除两个字符串中的常用字母? [英] How to remove common letters in two Strings in iOS SDK?

查看:131
本文介绍了如何在iOS SDK中删除两个字符串中的常用字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can i remove common letters in two strings and generate a new string using remaining unique letters ?

例如:

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

新字符串应为: Djaha

推荐答案

只需枚举字符串中的字符并删除匹配范围即可。一定要搜索'无壳'(即大写和小写字母之间的区别是无关紧要的)。以下片段记录了Djaha,正如开场白预期的那样。

Just enumerate through the characters in the string and delete matching ranges. Be sure to search 'caselessly' (ie the difference between uppercase and lowercase letters is irrelevant). The following snippet logs "Djaha", as the opening post expects.

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:

If this is a common operation, I would place the code into a category, with a method name like stringByRemovingMatchingCharactersInString:

这篇关于如何在iOS SDK中删除两个字符串中的常用字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆