c#从数组

时间:2015-06-12 16:54:20

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

以上代码段来自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;
    }

3 个答案:

答案 0 :(得分:4)

你所做的一切都没有错。这应该工作得很好。话虽如此,在C#中我们也有linq。您可以选择char[]并执行:

char[] result = inputCharArray.Distinct().ToArray();

答案 1 :(得分:0)

您的代码正确且功能完美,您也可以在C#中使用LINQ

stringName.Distinct()

dotnetperls使用两个变量的原因是因为它是一个介绍,并尝试尽可能简单地遵循逻辑以便于学习。好抓!

答案 2 :(得分:0)

由于两种方式都可以正常工作,因此并不是必需的。选择完全取决于开发人员。