Removing duplicate substrings inside a string in C #

How to remove duplicate substrings inside a string? therefore, for example, if I have a line like smith:rodgers:someone:smith:white , then how can I get a new line that has an extra smith deleted like smith:rodgers:someone:white . I would also like to keep colons, even if they are duplicated.

thank you very much

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

Of course, this code assumes that you are only looking for duplicate field values. This will not remove smithsmith in the following line:

 "smith:rodgers:someone:smithsmith:white" 

One could write an algorithm to do this, but it is rather difficult to make it efficient ...

+20
source

Something like that:

 string withoutDuplicates = String.Join(":", myString.Split(':').Distinct().ToArray()); 
+8
source

Assuming the format of this line:

 var theString = "smith:rodgers:someone:smith:white"; var subStrings = theString.Split(new char[] { ':' }); var uniqueEntries = new List<string>(); foreach(var item in subStrings) { if (!uniqueEntries.Contains(item)) { uniqueEntries.Add(item); } } var uniquifiedStringBuilder = new StringBuilder(); foreach(var item in uniqueEntries) { uniquifiedStringBuilder.AppendFormat("{0}:", item); } var uniqueString = uniquifiedStringBuilder.ToString().Substring(0, uniquifiedStringBuilder.Length - 1); 

Very long, but shows the process of transition from one to another.

+2
source

not sure why you want to keep duplicate colons. if you expect the output to be " smith:rodgers:someone::white ", try this code:

  public static string RemoveDuplicates(string input) { string output = string.Empty; System.Collections.Specialized.StringCollection unique = new System.Collections.Specialized.StringCollection(); string[] parts = input.Split(':'); foreach (string part in parts) { output += ":"; if (!unique.Contains(part)) { unique.Add(part); output += part; } } output = output.Substring(1); return output; } 

Of course, I did not check for null input, but I'm sure I will do it;)

0
source

All Articles