2
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;
    }
1
  • I don't think you are missing anything. result and table should have the same value at all times (barring the gap between the two lines that update them). Commented Jun 12, 2015 at 16:56

3 Answers 3

5

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Ah, ya beat me to posting! Your answer has better code example as well.
Thank you @pquest! I was staring at the solution and was "bothered" by something about it. Thank you for confirming. Thank you guys (@Daniel Hoffmann-Mitscherling and @pquest) for the linq example as well!
No problem! I really recommend looking into linq. it is really powerful for filtering through collections quickly.
0

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!

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.