Home > database >  How do I replace multiple elements?
How do I replace multiple elements?

Time:11-02

For example,

    string myString1 = "abcdef";
    string myString2;
    myString2 = myString1.Replace("a", "abc").Replace("b", "bcd");

The output will be "abcdcbcdcdef". I want my output to be "abcbcdcdef". I know that you could do that with a StringBuilder, but is there a shorter version? I need to do this with a large number of characters (> 100).

CodePudding user response:

The simplest approach is probably to loop over the characters of the string:

string myString1 = "abcdef";
StringBuilder result = new StringBuilder();
foreach (char c in myString1)
{
    if (c == 'a') // if the character is a, append abc
    {
        result.Append("abc");
    }
    else if (c == 'b') // if the character is b, append bcd
    {
        result.Append("bcd");
    }
    else // otherwise append the character verbatim
    {
        result.Append(c);
    }
}
string myString2 = result.ToString(); // produce a string from the StringBuilder

This produces "abcbcdcdef" as desired.


Another approach would be to use regular expressions with a custom evaluator:

string myString1 = "abcdef";
string myString2 = Regex.Replace(myString1, "[ab]", new MatchEvaluator(
    m => m.Value switch {
        "a" => "abc", 
        "b" => "bcd", 
        _ => m.Value 
    })
);

The regex [ab] will match the character a or the character b and pass this to the evaluator in m.Value. You could use ranges here (e.g. [a-z]), which would pass any character in the alphabet to the evaluator method. Since our "other" part of the switch statement just returns the original value, you can use ranges that are larger than you actually want to replace values for.

This also produces "abcbcdcdef".

  • Related