Add String to existing string if specific characters are found

I want to add concrete String

to the existing String

when the current String

has one of the following characters: =

, +

, -

, *

or /

.

For example, I want to add a test String

to this existing one String

: "= ABC + DEF"

The result String

should be: "= testABC + testDEF"

My first version looks like this and I want it to work, but the code is ugly

string originalFormula;
string newFormula1 = originalFormula.Replace("=", "=test");
string newFormula2 = newFormula1.Replace("+", "+test");
string newFormula3 = newFormula2 .Replace("-", "-test");
string newFormula4 = newFormula3 .Replace("*", "*test");
string newFormula5 = newFormula4 .Replace("/", "/test");

      

Is there a shorter way to achieve it?

+3


source to share


2 answers


If you want your code to be a little more elegant, go for Regex.

using System.Text.RegularExpressions;

string originalFormula = ...;
var replacedString = Regex.Replace(myString, "[-+*/=]", "$&test");

      



For a better understanding: [-+*/=]

groups the characters you want to check for a string. $&test

Replaces the found charackter with its match ( $&

) and appends to it test

.

+5


source


If your problem is that your code looks ugly, perhaps you can rewrite it to use a list ...



List<char> characters = new List<char> { '+', '-', '*', '/' };

foreach (var c in characters)
{
    string newValue = String.Format("{0}{1}", c, somethingElse);
    if (originalForumla.Contains(c);
    {
        newForumla = originalFormula.Replace(c, newValue);
    }
}

      

-1


source







All Articles