1

I'm trying to build a sentence which I'll use in SQL. Since where could be human errors and people putting more than one ',' in a sentence i wanted to as if there's a possibility to replace many same characters only into a singular one I.E.

string text = "lala,,,lala,,,,sdad,,,,123,,,,asd,,"

to turn it into

"lala,lala,sdad,123,asd"

?

JustasG
  • 31
  • 5
  • text.Replace(",,", ",").Trim(",")? – kriss May 09 '19 at 07:41
  • 1
    Possible duplicate of [Replace consecutive characters with same single character](https://stackoverflow.com/questions/3971412/replace-consecutive-characters-with-same-single-character) – GSerg May 09 '19 at 07:42
  • 1
    `could be human errors and people putting more than one ',' in a sentence` - and people putting [something more](https://stackoverflow.com/q/332365/11683) in that sentence. – GSerg May 09 '19 at 07:43
  • i've already made adjustments of changing other symbols to ',' thats why i would need to replace them to singular – JustasG May 09 '19 at 07:45
  • Actually, more precise would be a Possible duplicate of [Regex to remove multiple consecutive commas and replace with single comma](https://stackoverflow.com/q/46119102/11683) – GSerg May 09 '19 at 07:48
  • @kriss yeah i could replace it like that using a cycle but i was thinking maybe theres a different way with ome kind of Regex or smthng – JustasG May 09 '19 at 07:48

2 Answers2

0

Try with this code:

string text = "lala,,,lala,,,,sdad,,,,123,,,,asd,,";
text = string.Join(",", text.Split(',').Where(s => s != ""));
asd
  • 854
  • 7
  • 10
  • Of all possible ways to solve this problem, this one has to be one of the absolute worst. Not only it unnecessarily uses `Split` and `Join`, it even fails to benefit from [`StringSplitOptions.RemoveEmptyEntries`](https://learn.microsoft.com/en-us/dotnet/api/system.stringsplitoptions?view=netframework-4.8) while doing so. – GSerg May 09 '19 at 10:54
0
using System.Text.RegularExpressions;

string text = "lala,,,lala,,,,sdad,,,,123,,,,asd,,";

string result = Regex.Replace(text, ",+", ",").TrimEnd(new char[]{','});
Ricky
  • 103
  • 7