Saturday, 23 November 2024

Remove Duplication in the string

 //Word duplication checking

string s = "eearr";

string duplicatewords=string.Empty;

for (int i = 0; i < s.Length; i++)

{

    if (!(duplicatewords.Contains(s[i].ToString())))

    {

        duplicatewords += s[i];

    }

}

Console.WriteLine(duplicatewords);


Output:


Using LINQ for Duplication

//To Get unique Word alone
var a1 = s.GroupBy(x => x.ToString());

OUTPUT: a1[0]=e ,a1[1]=a,a1[2]=r

//To Get duplicate Values alone
var a = s.GroupBy(x => x.ToString())
              .Where(g => g.Count() > 1)
              .Select(y => y.Key)
              .ToList();

OUTPUT: a[0]=e ,a[1]=r

No comments:

Post a Comment