简体   繁体   English

删除两个字符串之间的匹配字符

[英]Removing matching characters between two strings

I want to remove the characters which are matching between the two given strings. 我想删除两个给定字符串之间匹配的字符。 Eg. 例如。

string str1 = "Abbbccd";
string str2 = "Ebbd";

From these two strings I want the output as: 从这两个字符串中,我希望输出为:

"Abcc" , only those many matching characters should be removed from str1,which are present in str2. "Abcc" ,仅应从str2中存在的那些许多匹配字符中删除。

I tried the following code: 我尝试了以下代码:

   public string Sub(string str1, string str2)
   {
       char[] arr1 = str1.ToCharArray();
       char[] arr2 = str2.ToCharArray();

       char[] arrDifference = arr1.Except(arr2).ToArray();
       string final = new string(arrDifference);

       return final;
   }

With this code I get the output as "Ac" . 使用此代码,我得到的输出为"Ac" It removes all the matching characters between two arrays and stores 'c' only once. 它删除两个数组之间的所有匹配字符,并且只存储一次“ c”。

First create this helper method: 首先创建此辅助方法:

IEnumerable<Tuple<char, int>> IndexDistinct(IEnumerable<char> source)
{
    var D = new Dictionary<char, int>();
    foreach (var c in source)
    {
        D[c] = D.ContainsKey(c) ? (D[c] + 1) : 0;
        yield return Tuple.Create(c, D[c]);
    }
}

It converts a string "aabcccd" to [(a,0),(a,1),(b,0),(c,0),(c,1),(c,2),(d,0)]. 它将字符串“ aabcccd”转换为[[a,0),(a,1),(b,0),(c,0),(c,1),(c,2),(d,0) ]。 The idea is to make every character distinct by adding a counting index on equal characters. 这个想法是通过在相等的字符上添加计数索引来使每个字符都不同。

Then modify your proposed function like this: 然后像这样修改您建议的功能:

string Sub(string str1, string str2)
{
    return new string(
        IndexDistinct(str1)
            .Except(IndexDistinct(str2))
            .Select(x => x.Item1)
            .ToArray());
}

Now that you are doing Except on Tuple<char, int> instead of just char , you should get the behavior you specified. 现在,您正在对Tuple<char, int>进行Except操作Tuple<char, int>而不只是对char ,您应该获得指定的行为。

You can do it with lists as well: 您也可以使用列表进行操作:

    List<char> one = new List<char>("Abbbccd".ToCharArray());
    List<char> two =  new List<char>("Ebbd".ToCharArray());
    foreach (char c in two) {
        try { one.RemoveAt(one.IndexOf(c)); } catch { }
    }
    string result = new string(one.ToArray());

Use C#'s string commands to modify the string. 使用C#的string命令修改字符串。

    public string testmethod(string str1, string str2)
    {
        string result = str1;
        foreach (char character in str2.ToCharArray())
        {
            result = result.Replace(character.ToString(), "");
        }

        return result;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM