我们有两个字符串,string first="abcdeabcde" 和 string second="cdefgcdefg"。
什么是最快/最有效的输入第三个字符串的方法,它只包含第一个字符串中可能的字符,例如string third="cdecde"?
更正式的例子:
- 第一个字符串包含集合
F={a,b,c,d,e}中的字符> - 第二个字符串包含字符
S={c,d,e,f,g}
我想知道如何快速从集合 S\(S\F)= S intersection F 中派生第三个字符串。
即字符串 second 包含字符串交集的字符。
第二个例子:
- 字符串 w="aaabbbccc"
- 字符串 z="bbbcccddd"
- 预期结果:字符串 y="bbbccc"即第二个字符串,但只有第一个字符串中的字符 b、c
第三个例子:
- string a="ABCDABCDBABDBC"- 来自 aplhabet {A,B,C,D} 的随机内容
- string b="CDEDECEDCDE"- 来自字母表 {C,D,E} 的随机内容
- final string f="CDDCDCD"- 删除所有出现的 {E}
请您参考如下方法:
string first = "abcdeabcde";
string second = "cdefgcdefg";
string intersection = String.Concat(first.Intersect(second));
string result = String.Concat(first.Where(c => intersection.Contains(c)));
Console.WriteLine(result); //output "cdecde"
解释:
Intersect扩展方法返回 IEnumerable<char>仅包含两个字符串中都存在的字符,为了将其转换为字符串,Concat方法连接所有成员并返回结果字符串。
编辑
现在只有交集中存在的字符应该保留在字符串 first 中
