如何将方程“x ^ 2 + x ^ 2 + 2x-x-25”中的变量的零系数转换为“+ 1x ^ 2 + 1x ^ 2 + 2x-1x-25”?

时间:2015-05-22 15:02:53

标签: java string math equations coefficients

这是我试图修正任何数学方程变量的系数 对于相同变量的和系数,如“x ^ 2 + x ^ 2 + 2x-x-25”为“+ 1x ^ 2 + 1x ^ 2 + 2x-1x-25”,然后将总和设为“2x” ^ 2 + x-25“,注意我已经用另一种方法完成了求和过程。

private static String fixCoeff(String equ)
{
    equ=equ.toLowerCase();//change equation variables to lower case
    equ=equ.trim();//remove white spaces
    String []characters={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
    int index=-1;
    String fixedCoeff="";
    for (int i = 0; i < characters.length; i++)
    {
        if(!equ.contains(characters[i]))
        {
            continue;
        }
        //if a not found in equ i++ 
        //if true execute this
        while(equ.indexOf(characters[i],++index)!=-1)
        {


            index=equ.indexOf(characters[i]);
            if(index==0)
            {
                fixedCoeff+="+1"+equ;
                equ=fixedCoeff;
                index=2;
                break;

            }
            else
            {

                if (equ.charAt(index-1)=='+'||equ.charAt(index-1)=='-')
                {
                    fixedCoeff=equ.substring(-1,index-1);
                    fixedCoeff+="1"+equ.substring(index-1,equ.length()-1);
                    equ=fixedCoeff;
                    index++;
                    break;
                }

            }

        //  if (index==equ.length()-1) {//if we found last element in equ is a variable
                //break;
            //}
        }//end while

    }//end for loop 


    return equ;

}//end fixCoeff

输入案例:

  1. a
  2. X
  3. X ^ 2
  4. 的x ^ 2 + X ^ 2
  5. 输出案例:

    1. + 1A
    2. + 1X
    3. + 1X ^ 2
    4. + 1X ^ 2 + 1×2 ^

2 个答案:

答案 0 :(得分:2)

只是加起来@ brso05回答,

这是另一种方式:

    String s ="x^2+x^2+2x-x-25";
    s=s.replaceAll("(?<!\\d)([a-z])", "1$1");    // <-- replaces any lower letters with 1 concatanted with the same letter
    if(!s.startsWith("-")){
        s="+"+s;  //<-- if the first character is not negative add a + to it.
    }
    System.out.println(s);

<强>输出:

+1x^2+1x^2+2x-1x-25

答案 1 :(得分:1)

使用String.replaceAll()这样可以更轻松地完成此操作:

for (int i = 0; i < characters.length; i++)
{
    if(!equ.contains(characters[i]))
    {
        continue;
    }
    equ = equ.replaceAll(("(?<!\\d)" + characters[i]), ("1" + characters[i]));
}
if(!equ.startsWith("-") && !equ.startsWith("+"))
{
    equ = "+" + equ;
}

这将替换前面没有数字的字符1x(或当前字符是什么)。这使用带有负向lookbehind的正则表达式来确保字符前面没有数字,然后它将替换为1(字符)。

以下是一个独立的示例:

String line = "x-x^2+3x^3";
line = line.replaceAll("(?<!\\d)x", "1x");
System.out.println("" + line);

这将输出1x-1x^2+3x^3