Reputation: 61
I want to detect and remove the duplications from string.
my code is here :
string Tests = "Hi,World,Me,Hi,You";
string[] Tests_Array = Tests.Split(',');
Regex FindDup = new Regex(@"(.+)\1", RegexOptions.IgnoreCase);
string t2 = "";
foreach (string test in Tests_Array)
{
MatchCollection allMatches = FindDup.Matches(test);
foreach (Match item in allMatches)
{
t2 = FindDup.Replace(test, string.Empty);
textBox1.Text += string.Format(@"Final: ""{0}""", t2) + "\n";
}
}
But it does not work.
I do not know where is the problem ?
Thanks for any help.
Upvotes: 2
Views: 151
Reputation: 5430
You could use LINQ
string Tests = "Hi,World,Me,Hi,You";
string[] Tests_Array = Tests.Split(',');
string result = String.Join(",", Tests_Array.Distinct());
Upvotes: 6
Reputation: 222582
You could simply do this,
var words = new HashSet<string>();
string text = "Hi,World,Me,Hi,You";
text = Regex.Replace(text, "\\w+", t => words.Add(t.Value.ToUpperInvariant())? t.Value: String.Empty);
Upvotes: 1