Insert character before specific character c #

Assuming the line below is in C #, how would I replace

y=x^7+3x^4-x+5

      

from

y=0^7+3*0^4-0+5

      

since one cannot just replace all instances x

with 0

as then you get30^4

+3


source to share


2 answers


var a = "y=x^7+3x^4-x+5";
var b = Regex.Replace(a, @"(\d+|[a-zA-Z])(?=\d+|[a-zA-Z])", @"$1*");
var c = Regex.Replace(b, @"x", @"0");

      

summery 2nd line : match any number or variable followed by any number or variable.

Output examples:



In: y=33xggyz/3/4*x/x+xx1         |  In: y=x^7+3x^4-x+5        
Out:y=33*x*g*g*y*z/3/4*x/x+x*x*1  |  Out:y=0^7+3*0^4-0+5              
                                  |
In: y=2+33xggyz/3/4*x/x+xx        |  In: y=x1
Out:y=2+33*0*g*g*y*z/3/4*0/0+0*0  |  Out:y=0*1
                                  |
In: y=10xy^2+xx+(12x+1yy)         |  In: y(xx)=1
Out:y=10*0*y^2+0*0+(12*0+1*y*y)   |  Out:y(0*0)=1

      

Updated: (7/4/2015) bug fixed, failed with y = x1 (returned y = 01)

+3


source


In this case, when you just want to o change

y=x^7+3x^4-x+5

      

to

y=0^7+3*0^4-0+5

      



It would be easy to add another variable.

int x = //Whatever x is going to be;
int j = 0;
int y = j^7+3x^4-j+5

      

Now, if you have more user cases than just this one, you can add a lot of variables, in which case you don't want to use this parameter. But if you are using it for an isolated case, this might be a viable answer.

0


source







All Articles