C# 从数组中删除重复的字符

Dav*_*Ops 2 c# arrays string char

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;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码片段来自http://www.dotnetperls.com/duplicate-chars。我的问题是,result当您可以使用时,为什么还需要额外的变量table?这两个变量都有原因吗?我相信下面是我编写的代码,可以实现相同的目的。我错过了什么吗?再次感谢并期待在这里做出贡献!

重写代码:

        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;
    }
Run Code Online (Sandbox Code Playgroud)

pqu*_*est 5

你所做的并没有什么问题。那应该工作得很好。话虽这么说,在 C# 中我们也有 linq。你可以采取 achar[]并执行以下操作:

char[] result = inputCharArray.Distinct().ToArray();
Run Code Online (Sandbox Code Playgroud)