Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicate substrings within a string in C#

Tags:

c#

How can I remove duplicate substrings within a string? so for instance if I have a string like smith:rodgers:someone:smith:white then how can I get a new string that has the extra smith removed like smith:rodgers:someone:white. Also I'd like to keep the colons even though they are duplicated.

many thanks

like image 222
Josh Avatar asked Aug 27 '10 16:08

Josh


1 Answers

string input = "smith:rodgers:someone:smith:white";
string output = string.Join(":", input.Split(':').Distinct().ToArray());

Of course this code assumes that you're only looking for duplicate "field" values. That won't remove "smithsmith" in the following string:

"smith:rodgers:someone:smithsmith:white"

It would be possible to write an algorithm to do that, but quite difficult to make it efficient...

like image 95
Thomas Levesque Avatar answered Sep 28 '22 08:09

Thomas Levesque