简体   繁体   English

想在某些条件下使用 java 删除部分字符串

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

I am trying to generate simultaneous equations question in Java.我正在尝试在 Java 中生成联立方程问题。 I am generating x, y, xc1 & xc2 (coefficents of x) and yc1 & yc2 (coefficients of y) using Random rand=new Random();我正在使用 Random rand=new Random(); 生成 x、y、xc1 & xc2(x 的系数)和 yc1 & yc2(y 的系数);

Whenever the coefficient of x or y is 1 I want it to be removed from the string.每当 x 或 y 的系数为 1 时,我都希望将其从字符串中删除。

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我试过string.replace()方法,但它不起作用

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:只需将正则表达式与 replaceAll 一起使用:

showQuestion = showQuestion.replaceAll("\\b1([xy])", "$1");
  • \\b word boundaries, so 21 is not replace to 2. \\b字边界,因此 21 不会替换为 2。
  • [xy] either x or y. [xy] x 或 y。
  • (...) group $1 (next would be $2 etcetera). (...) 1 美元组(接下来是 2 美元等)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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