c# remove duplicate char from array

1.9k Views Asked by At
static string RemoveDuplicateChars(string key)
{
// --- Removes duplicate chars using string concats. ---
// Store encountered letters in this string.
string table = "";

// Store the result in this string.
string result = "";

// Loop over each character.
foreach (char value in key)
{
    // See if character is in the table.
    if (table.IndexOf(value) == -1)
    {
    // Append to the table and the result.
    table += value;
    result += value;
    }
}
return result;
}

The above code-snippet is from http://www.dotnetperls.com/duplicate-chars. The question I have is why do you need the extra result variable when you can just use table? Is there a reason for both variables? Below is code I wrote that accomplishes the same purpose, I believe. Am I missing anything? Thanks again and look forward to contributing here!

Code re-written:

        static string RemoveDuplicateChars(string key)
    {
        // --- Removes duplicate chars using string concats. ---
        // Store encountered letters in this string.
        string table = "";

        // Loop over each character.
        foreach (char value in key)
        {
            // See if character is in the table.
            if (table.IndexOf(value) == -1)
            {
                // Append to the table and the result.
                table += value;
            }
        }
        return table;
    }
3

There are 3 best solutions below

3
On BEST ANSWER

There is nothing wrong with what you did. That should work just fine. That being said, in C# we also have linq. You could just take a char[] and do:

char[] result = inputCharArray.Distinct().ToArray();
0
On

Your code is correct and functions perfectly, you could also use LINQ in C# using

stringName.Distinct()

The reason that dotnetperls uses two variables is because it is an introduction, and tries to the logic as straightforward as possible to follow to facilitate learning. Good catch!

0
On

It is not really necessary as both ways work fine. The choice is purely up to the developer.