3

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 ?

8
  • 1
    If that works you should use it. You will definitely not find anything shorter, more efficient or more readable. Commented Jun 26, 2017 at 9:05
  • Because Replace returns the updated string, you could just chain each Replace call: string newFormula = originalFormula.Replace("=", "=test").Replace("+", "+test").Replace("-", "-test").Replace("*", "*test").Replace("/", "/test"); - I don't know if it makes it more readable though. Commented Jun 26, 2017 at 9:09
  • Alternatively, this question shows how to use a dictionary of search-replace pairs that might be helpful - stackoverflow.com/questions/1231768/… Commented Jun 26, 2017 at 9:10
  • @TimSchmelter I will say that it is more readable (lol, semi-irony)... The regex is "[=+*/-]", the replacement is "$$test"... See regexstorm.net/tester?p=%5b%3d%2b*%2f-%5d&i=%3dABC%2bDEF&r=%24%24test . Commented Jun 26, 2017 at 9:10
  • 2
    I'm voting to close this question as off-topic because OP tries to improve working code(it's even unclear why he needs to improve it) Commented Jun 26, 2017 at 9:23

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

If your problem is that your code looks ugly maybe you could rewrite it to use a list rather...

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.