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

c# remove duplicate char from array

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# 中使用 LINQ

stringName.Distinct()

dotnetperls之所以用两个变量是因为是介绍,尽量逻辑通俗易懂,方便学习。抓得好!

这两种方法都可以正常工作,所以没有必要。选择完全取决于开发人员。