RahulD
RahulD

Reputation: 709

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.

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". It removes all the matching characters between two arrays and stores 'c' only once.

Upvotes: 0

Views: 2248

Answers (3)

jiverson
jiverson

Reputation: 1234

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());

Upvotes: 3

Craig
Craig

Reputation: 94

Use C#'s string commands to modify the string.

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

        return result;
    }

Upvotes: 0

Timothy Shields
Timothy Shields

Reputation: 79461

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)]. 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.

Upvotes: 3

Related Questions