Home > Software design >  Easy formatting of a string instead of using repetitive "Replace"
Easy formatting of a string instead of using repetitive "Replace"

Time:12-01

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.

CodePudding user response:

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);

CodePudding user response:

It looks like you want to remove the substrings, not replace them. You can use this extension method:

public static class RemoveExtensions
{
    public static string RemoveMultiple(this string str, params string[] removes)
    {
        foreach (string s in removes)
        {
            str = str.Replace(s, "");
        }
        return str;
    }
}

Use it like this:

string x = "[\r\n  \"TEST\",\r\n  \"GREAT\"\r\n]";
string result = x.RemoveMultiple("\r\n", "[", "]");

CodePudding user response:

First of all, create a helper method to hide this:

public static string ExtractLetters(this string text) // it's an extension method
{
    return text.Replace("\r\n", "").Replace("[", "")....;
}

now you can use it like this:

var extracted = "[\r\n \"TEST\",\r\n \"GREAT\"\r\n]".ExtractLetters()

already a bit better.

Since I think your goal isn't really to replace things, just etract what you want, you can use regex:

using System.Text.RegularExpressions;

public static string ExtractLetters(this string text)
{
    var regex = new Regex("[a-zA-Z] "); // define regex, look for regex compilation and instance caching for optimizations here
    string[] matches = regex.Matches(text).Select(x => x.Value).ToArray(); // extract matches
        
    return string.Join(",", matches); // join them if you want
}

To develop the regex, use a website like https://regex101.com/

  • Related