开发者

How to check the duplicate characters from string2 in string1 and then remove it?

e.g String1 = "Hello";
e.g String2 = "eo";

I want to remove all chars in string1 that are in 开发者_运维知识库string2.

So the output should be "Hll"


Not the most efficient but a very readable solution:

string input = "hello";
string dupes = "eo";

var output = new string((from c in input where !dupes.Contains(c) select c).ToArray());

A more efficient approach for large strings would be using a Hashset<char> for the dupes:

string input = "hello";
string dupes = "eo";

HashSet<char> dupeSet = new HashSet<char>();
foreach (char c in dupes)
    dupeSet.Add(c);

var output = new string(input.Where(c => !dupeSet.Contains(c)).ToArray());


If I understand you correctly, you could do it using LINQ like this:

new string(string1.Where(c => !string2.Contains(c)).ToArray())

For your examples, this returns "Hll".

If you want to get a collection of all characters from string1 that are not in string2, that's even simpler:

string1.Except(string2)


string1 = new string(string1.Where(x => !string2.Contains(x)).ToArray());

result:

string1 = "Hll"


A classic approach (without LINQ) is:

string String1 = "Hello", String2 = "eo";

for (int i = 0; i < String2.Length; i++)
{
    String1 = String1.Replace(String[i] + "", ""); // replace them with empty string
}

The result is:

String1 = "Hll"


String result = String.Join("", String1.Split(String2.ToCharArray()));

It might not be efficient, but it is a solution for small strings.


    string string1 = "hello";
    string string2 = "eo";

    string1 = Regex.Replace(string1, "[" + string2 + "]", "");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜