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

标签 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 。我的问题是,当您可以只使用 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/

相关文章:

c - C 语言中的一堆单词(回文句)

c# - 通用 TypeCode 类型检查?

c# - 非静态字段、方法或属性需要对象引用

c# - 更改文本到语音语音的性别

c++ - 数组段错误

我可以在 C 中将数字常量与字符串连接起来吗?

c# - Linq 在没有 .GroupBy() 的情况下获取不同的有序元素

java - 将每个值映射到 Java 数组(或类似数组)中,就像在 Ruby 中一样

javascript - 按索引对字符串数组进行排序

javascript - 字符串操作,删除标签