I want to parse numbers from a String.
Example input String: 0 = 2*x+2*x^2-4
Transform to:
leftside = 0
rightside = 2*x,2*x^2,-4
Finally I want to save the numbers in variables like leftN = 0
, rightX = 2
How can this be done? Any hints?
I want to parse numbers from a String.
Example input String: 0 = 2*x+2*x^2-4
Transform to:
leftside = 0
rightside = 2*x,2*x^2,-4
Finally I want to save the numbers in variables like leftN = 0
, rightX = 2
How can this be done? Any hints?
First you can split the string into two, LHS anf RHS by using method split()
method signature looks like this,
public String[] split(String regex, int limit) //limit: maximum strings splited
or
public String[] split(String regex)
Simple example maybe,
String[] str_array = "0 = 2*x+2*x^2-4".split(" = ");
String LHS = str_array[0];
String RHS = str_array[1];
Further keep splitting the RHS string and get it as maybe elements[]
by splitting with -
and +
so you can further divide and get the RHS as terms.
for getting numbers as int
s you can use,
try{
Integer.parseInt(elements[i]);
}catch(NumberFormatException e){
parsable = false;
}
Split your string with the char you want it in to be different
String[] s = display.split("=");
If you're wanting to retrieve values of 0 and 2, you can use the split()
method further to retrieve the exact values:
String display = "0 = 2*x+2*x^2-4";
int leftN = Integer.parseInt(display.split("=")[0].trim());
int rightX = Integer.parseInt(display.split("=")[1].trim().split("\\*")[0].trim());
System.out.println(leftN + ", " + rightX);
//output: 0, 2
The first line retrieves the first value from the split at =
.
The second line retrieves the second value from the split at =
, and then splits all cases of *
. It retrieves the first value from that split. trim()
is to ensure there are no white-spaces, which woud result in a NumberFormatException
.
However, if you're not wanting the values to be of int
value:
String display = "0 = 2*x+2*x^2-4";
String leftN = (display.split("=")[0].trim();
String rightX = display.split("=")[1].trim().split("\\*")[0].trim();
System.out.println(leftN + ", " + rightX);
//output: 0, 2
Further, if you're wanting to grab the 2
at the x^2
portion of the equation:
String rightX = display.split("\\^")[1].trim().split("-")[0].trim();