-7

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?

pre
  • 3,475
  • 2
  • 28
  • 43
MarvinJoke
  • 97
  • 1
  • 7
  • String splitting and number parsing. – Compass Dec 18 '14 at 14:56
  • To get the actual numbers you have to make an evaluator. Google for it – Charlie Dec 18 '14 at 15:02
  • You can also refer to this [SO Question](http://stackoverflow.com/questions/9785553/how-does-a-simple-calculator-with-parentheses-work) or [Shunting Yard Algorithm](http://en.wikipedia.org/wiki/Shunting-yard_algorithm) for more information (note: totally advanced compared to your question). – Buhake Sindi Dec 18 '14 at 15:06
  • What are you trying to achieve? Obtaining the polynomial degree for each side? Your question is vague. – mbomb007 Dec 18 '14 at 15:11

3 Answers3

2

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 ints you can use,

try{
   Integer.parseInt(elements[i]);
}catch(NumberFormatException e){
   parsable = false;
}
Dinal24
  • 3,162
  • 2
  • 18
  • 32
0

Split your string with the char you want it in to be different

String[] s = display.split("=");
deejay
  • 575
  • 1
  • 8
  • 24
0

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();
Drew Kennedy
  • 4,118
  • 4
  • 24
  • 34