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;
}
上面的代码片段来自http://www.dotnetperls.com/duplicate-chars 。我的问题是,当您可以只使用 table
时,为什么还需要额外的 result
变量?这两个变量都有原因吗?我相信下面是我编写的代码,可以实现相同的目的。我错过了什么吗?再次感谢并期待在这里做出贡献!
重写代码:
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;
}
最佳答案
你所做的事情没有任何问题。那应该工作得很好。话虽这么说,在 C# 中我们也有 linq。您可以只使用 char[]
并执行以下操作:
char[] result = inputCharArray.Distinct().ToArray();
关于C# 从数组中删除重复的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30808415/