I want to replace the "cube root of" and "square root of" in a String to respectively "^(1/3)" and "^(1/2)", but after the operand.
Making a simple replace would put "^(1/3)" and "^(1/2)" ahead of the numbers, but I need them to be after the numbers (I am working with an ExpressionBuilder API from exp4j, which requires this).
For example, given this string:
"cube root of 27 times cube root of 64 plus square root of 9 minus square root of 4"
I want it to be converted to:
"27^(1/3)*64^(1/3)+9^(1/2)-4^(1/2)"
Here's my attempt:
String equation = "cube root of 27 times square root of 45";
String r1 = equation.replaceAll("cube root of", "◊").replaceAll("square root of", "√")
.replaceAll("times", "*").replaceAll("plus", "+").replaceAll("minus", "-")
.replaceAll("divided by", "/").replaceAll(" ", "");
System.out.println(r1);
String r2 = null;
if (r1.contains("◊"))
{
for (int i = r1.indexOf("◊")+1; i < r1.length(); i++)
{
if(Character.isDigit(r1.charAt(i)))
{
}
else
{
System.out.println("i: " + i);
r2 = r1.substring(r1.indexOf("◊")+1, i) + "^(1/3)" + r1.substring(i);
break;
}
}
}
System.out.println(r2);
I've replaced a temporary character "◊" for "cube root of" (gets tedious writing the whole phrase out), and I've gotten it to work for me where the output I get is:
◊27*√45
i: 3
27^(1/3)*√45
So it works only for one "cube root of" phrase, not two, and fails to work the "square root of" phrase (It's not in the code, but I tried incorporating this in my code in the first if() block where I see if the String contains the "◊" symbol.
I tried using the OR r1.contains("√") operator in that if() block, but it screwed things up with my existing code. I have looked everywhere online for a solution. I've tried methods such as a replaceCharAt(String s, int position, char c) in my program to replace the character at the specified position, but I couldn't get it to work with all occurrences of the specified phrases.
I've spent weeks on finding a solution, but I can't find one in which I can replace BOTH phrases for a mathematical operation.
I would greatly appreciate any help posted here.