Introduction
In this blog, we will learn how to remove duplicate words from the String using for loop in C#.
Add namespace using System.Text
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();
using Linq
Add namespace using System.Linq
string str = "One Two Three One";
string[] arr = str.Split(' ');
Console.WriteLine(str);
var a =
from k in arr
orderby k
select k;
Console.WriteLine("After removing duplicate words...");
foreach(string res in a.Distinct()) {
Console.Write(" " + res.ToLower());
}