Better way to add spaces between double semicolons

You can try to Split string into the parts, then replace empty entries with spaces using Select (it requires using System.Linq;) and Join the entries back

var str = "A;B;;;;C";
var parts = str.Split(';').Select(p => string.IsNullOrEmpty(p) ? " " : p);

var result = string.Join(";", parts);

The output will be the following A;B; ; ; ;C

Benchmark result in comparison with OP code and Regex solution:

enter image description here

What is the clear and more elegant is up to you decision. Benchmark code for the reference is below

[SimpleJob]
public class Benchmark
{
    string input= "A;B;;;;C";

    [Benchmark]
    public string SplitJoinTest()
    {
        var parts = input.Split(';').Select(p => string.IsNullOrEmpty(p) ? " " : p);
        return string.Join(";", parts);
    }

    [Benchmark]
    public string DoubleReplaceTest()
    {
        return input.Replace(";;", "; ;").Replace(";;", "; ;");
    }

    [Benchmark]
    public string RegexTest()
    {
        return Regex.Replace(input, ";(?=;)", "; ");
    }
}

One way is to use regular expressions.

using System.Text.RegularExpressions;

var result = Regex.Replace("A;B;;;;C;", ";(?=;)", "; ");

We replace every semicolon that is followed by another semicolon with the string "; ".

It's definitely less redundant, and it's clear if you know how to read regex :) Whether it is more elegant is up to you to decide.

Tags:

C#

String

Replace