简体   繁体   中英

Want to remove part of the string under certain conditions using java

I am trying to generate simultaneous equations question in Java. I am generating x, y, xc1 & xc2 (coefficents of x) and yc1 & yc2 (coefficients of y) using Random rand=new Random();

Whenever the coefficient of x or y is 1 I want it to be removed from the string.

Eg.

Currently it is showing

1x+2y=5

which I want to change into

x+2y=5

I have tried string.replace() method but it is not working

showQuestion = xc1+ "x"+ " + " +yc1+ "y" + " = " +product1 + "\r\n" + xc2+ "x" + " + " + yc2+ "y" +" = " + product2;

 //product1=x*xc1+y*yc1
 //product2=x*xc2+y*yc2

if (xc1==1)
{
    showQuestion = showQuestion.replace("xc1+ ","");
}
if (xc2==1)
{
    showQuestion = showQuestion.replace("xc2+ ","");
}
if (yc1==1)
{
    showQuestion = showQuestion.replace("yc1+ ","");
}
if (yc2==1)
{
    showQuestion = showQuestion.replace("yc2+ ","");
}

Just use a regular expression with replaceAll:

showQuestion = showQuestion.replaceAll("\\b1([xy])", "$1");
  • \\b word boundaries, so 21 is not replace to 2.
  • [xy] either x or y.
  • (...) group $1 (next would be $2 etcetera).

More strict would have been

showQuestion = term(xc1, "x") + term(yc1, "y") + " = " + product1 + "\r\n"
    + term(xc2, "x") + term(yc2, "y") + " = " + product2;

String term(int coeff, String var) {
    if (coeff == 0) {
        return "";
    }
    return (coeff < 0 ? " - " : " + ")
        + (coeff == 1 ? "" : String.valueOf(Math.abs(coeff)))
        + var;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM