Search code examples
c#arraysstringstring-formatting

Easy formatting of a string instead of using repetitive "Replace"


Is there a shortcut in replacing characters in a string? My string is like this:

string x = "[\r\n  \"TEST\",\r\n  \"GREAT\"\r\n]";

I want to have an output of only

TEST,GREAT

Right now I'm formatting it like: x..Replace("\r\n", "").Replace("[", "") and until I put all the characters.

My question is there a shortcut to do that instead of many "Replace"? It does not matter if it will be a string or put in a List of string. As long as I have the result TEST,GREAT.


Solution

  • This looks like formatted JSON. So you could treat it as such!

        string x = "[\r\n  \"TEST\",\r\n  \"GREAT\"\r\n]";
    
        // Parse JSON to a list (could be anything implementing IEnumerable<>) of strings
        var words= System.Text.Json.JsonSerializer.Deserialize<List<string>>(x);
    
        // And join the values back together with a comma
        var result = string.Join(',', words);
    
        Console.WriteLine(result);