3

I have a string like "abc,,bcd,";

The output should be abc,bcd i.e. the extra commas should be removed.

Help needed

Jeff Atwood
  • 62,295
  • 46
  • 147
  • 153

5 Answers5

10
string result = Regex.Replace(input, ",+", ",").Trim(',');
mmx
  • 402,675
  • 87
  • 836
  • 780
1
string input = "abc,,bcd,";
string output = String.Join(",",
    input.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
);
Carlos Muñoz
  • 16,721
  • 7
  • 55
  • 78
0

How about something like

string s = "abc,,bcd,";
s = s.Trim(',');
while (s.Contains(",,"))
    s = s.Replace(",,", ",");
Adriaan Stander
  • 156,697
  • 29
  • 278
  • 282
  • I'd like to point out that this approach can be dangerous in some cases (leading to infinite loop). See http://stackoverflow.com/questions/1279859/how-to-replace-multiple-white-spaces-with-one-white-space/1279900#1279900 – mmx Dec 10 '10 at 04:53
  • Lets hope that the asian comma is not to different to the english one X-) – Adriaan Stander Dec 10 '10 at 04:56
0

You can try splitting the string into an array. Then loop through the array. Check if the current element has a value you find acceptable. Append that value to a stringbuilder. If that is not the last element of the array, append a comma to the stringbuilder.

Jon Abaca
  • 801
  • 1
  • 8
  • 14
0
string input = "abc,,bcd,";

input.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Aggregate((a, b) => a + "," + b);
  • Simply use `string.Join` instead of `Aggregate`. It's more readable, and faster (concats all at once). – mmx Dec 10 '10 at 04:49