从 C# 中的字符串中删除重复的单词

本文关键字:单词 字符串 删除 | 更新日期: 2023-09-27 18:35:15

这是我的代码:

class Program
    {
        static void Main(string[] args)
        {
            string sentence = string.Empty;
            sentence = Console.ReadLine();
            string[] sent = sentence.Split(' ');
            //to be sorted alphabetically
            var x =
                from k in sent
                orderby k
                select k;
            foreach (string s in x)
            {
                    Console.WriteLine(s.ToLower());
            }
            Console.ReadLine();
        }
    }

有什么方法可以查找和删除重复的单词,或者我应该制作自己的方法?

从 C# 中的字符串中删除重复的单词

您可以使用

Linq 的Distinct扩展方法:

var sent = sentence.Split(' ').Distinct();

您还可以使用它在比较字符串时忽略字符串的大小写 - 例如 "WORD""word"将被视为重复项:

var sent = sentence.Split(' ').Distinct(StringComparer.CurrentCultureIgnoreCase);

Use System.Linq Distinct:

foreach (string s in x.Distinct())

使用不同:

foreach (string s in x.Distinct())
{
        Console.WriteLine(s.ToLower());
}

这应该可以满足您的要求:

class Program
{
    static void Main(string[] args)
    {
        string sentence = string.Empty;
        sentence = Console.ReadLine();
        var sent = sentence
            .Split(' ')
            .Distinct()
            .OrderBy(x => x);
        foreach (string s in sent)
        {
            Console.WriteLine(s.ToLower());
        }
        Console.ReadLine();
    }
}

希望对您有所帮助!

简单删除重复的单词 通过使用 for 循环形成字符串。试试这个,它工作正常。

string SetenceString = "red white black white green yellow red red black white";
        string[] data = SetenceString.Split(' ');
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < data.Length; i++)
        {
            string temp = " ";
            if (i == 0)
            {
                temp = data[i].ToString();
                sb = sb.Append(temp + " ");
            }
            else
            {
                for (int j = 1; j < data.Length; j++)
                {
                    string temp2 = data[j].ToString();
                    string strnew = sb.ToString();
                    string[] Kdata = strnew.Split(' ');
                    bool isnoduplicate = false;
                    for (int k = 0; k < Kdata.Length; k++)
                    {
                        string temp3 = Kdata[k].ToString();
                      if (temp3 != "")
                        {
                            if (temp2 == temp3)
                            {
                                isnoduplicate = false;
                                break;
                            }
                            else
                            {
                                isnoduplicate = true;
                            }
                        }
                    }
                    if (isnoduplicate)
                    {
                        sb = sb.Append(temp2 + " ");
                    }
                }
            }
        }
        Console.WriteLine(sb);
        Console.ReadKey();