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;
}
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: