Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add String into existing String whenever specific characters found

Tags:

string

c#

.net

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 ?

like image 816
Nuts Avatar asked Feb 14 '26 04:02

Nuts


1 Answers

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.

like image 51
Yggraz Avatar answered Feb 16 '26 19:02

Yggraz