I want to add a specific String into an existing String whenever the existing String contains one of the following characters: =, +, -, * or /.
For example, I want to add the String "test" into this existing String:
"=ABC+DEF"
Resulting String should be: "=testABC+testDEF"
My first version looks like this and I quess it works but 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 some shorter way to achive it ?
If you want your code a bit more elegant, go with Regex.
using System.Text.RegularExpressions;
string originalFormula = ...;
var replacedString = Regex.Replace(myString, "[-+*/=]", "$&test");
For better understanding:
[-+*/=] groups the charackters you want to check the string for. $&test Replaces the found charackter with its match ($&) and adds test to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With