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 + "]", "");
精彩评论