在字符串中查找重复的单词并删除重复项

时间:2015-08-12 08:20:41

标签: c# asp.net

我们说我的字符串中包含许多单词,例如:

string SetenceString= "red white black white green yellow red red black white"

我想删除所有dupplicates并仅返回每个单词一次:

SetenceString= "red white black green yellow"

我怎样才能用C#这样做?非常感谢所有帮助。

3 个答案:

答案 0 :(得分:6)

如果您的单词总是分开:

String.Join(" ", SetenceString.Split(' ').Distinct())

否则你应该使用正则表达式

答案 1 :(得分:6)

你甚至没有告诉我们你尝试了什么但是......

string SetenceString = "red white black white green yellow red red black white";
var result = string.Join(" ", SetenceString.Split(' ').Distinct());
Console.WriteLine(result);

输出将是;

  

红白黑黄绿

但是嘿,这究竟是如何运作的?

  • 我们将字符串与空格分开,以便将所有单词都放在字符串数组中。
  • 我们使用Distinct() method只获取字符串数组中的不同单词。
  • 我们使用string.Join将所有这些不同的字词与空格组合在一起。

答案 2 :(得分:0)

    string SetenceString = "red white black white green yellow red red black white";
    string[] data = SetenceString.Split(' ');
    HashSet<string> set = new HashSet<string>();
    for (int i = 0; i < data.Length; i++)
    {
        set.Add(data[i]);
    }

set varible现在只包含唯一的项目

相关问题