Search code examples
c#.netstringbuilder

remove string between "|" and "," in stringbuilder in C#


I use VS2019 in Windows7. I want to remove string between "|" and "," in a StringBuilder.

That is , I want to convert StringBuilder from

"578.552|0,37.986|317,38.451|356,23"

to

"578.552,37.986,38.451,23"

I have tried Substring but failed, what other method I could use to achieve this?


Solution

  • StringBuilder isn't really setup for much by way of inspection and mutation in the middle. It would be pretty easy to do once you have a string (probably via a Regex), but StringBuilder? not so much. In reality, StringBuilder is mostly intended for forwards-only append, so the answer would be:

    if you didn't want those characters, why did you add them?

    Maybe just use the string version here; then:

    var s = "578.552|0,37.986|317,38.451|356,23";
    var t = Regex.Replace(s, @"\|.*?(?=,)", ""); // 578.552,37.986,38.451,23
    

    The regex translation here is "pipe (\|), non-greedy anything (.*?), followed by a comma where the following comma isn't part of the match ((?=,)).