4

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
  • 63,320
  • 48
  • 150
  • 153

5 Answers5

10
string result = Regex.Replace(input, ",+", ",").Trim(',');
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
1

How about something like

string s = "abc,,bcd,";
s = s.Trim(',');
while (s.Contains(",,"))
    s = s.Replace(",,", ",");
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
  • 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 – Mehrdad Afshari 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
1
string input = "abc,,bcd,";
string output = String.Join(",",
    input.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
);
Carlos Muñoz
  • 17,397
  • 7
  • 55
  • 80
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
  • 821
  • 1
  • 9
  • 14
0
string input = "abc,,bcd,";

input.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Aggregate((a, b) => a + "," + b);