We use a Dictionary for constant-time look up. We will be processing words in a loop, and we need to check each word against all words already encountered.
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main()
{
string s =
"yellow bird, blue bird, yellow sun";
Console.WriteLine(s);
Console.WriteLine(RemoveDuplicateWords(s));
}
static public string RemoveDuplicateWords(string v)
{
// Keep track of words found in this Dictionary.
var d = new Dictionary<string, bool>();
// Buildup string into this StringBuilder.
StringBuilder b = new StringBuilder();
// Split the input.
string[] a = v.Split(new char[] { ' ', ',', ';', '.' }, StringSplitOptions.RemoveEmptyEntries);
// Loop over each word.
foreach (string current in a)
{
// Lowercase each word.
string lower = current.ToLower();
// If we haven't already encountered the word, append it to the result.
if (!d.ContainsKey(lower))
{
b.Append(current).Append(' ');
d.Add(lower, true);
}
}
// Return a string.
return b.ToString().Trim();
}
}
yellow bird, blue bird, yellow sun
yellow bird blue sun