-3

I am looking for a simple way to extract set of numbers from a string in Java.

For instance:

String temp = "120.6 + 220.4";

I want to extract "220.4" from the string and assing it to a double variable. Can anyone help me with a simple solution for this?

bmargulies
  • 97,814
  • 39
  • 186
  • 310
gozluklu_marti
  • 79
  • 1
  • 7
  • 26
  • 2
    Here's how you can extract "220.4" from a string: `public double get220point4(String s) {return 220.4;}`. Could you be more specific about your question? What happens for other strings that aren't "120.6 + 220.4"? – user253751 Feb 03 '14 at 00:34
  • 2
    why 220.4 and not 120.6? please be more specific – morgano Feb 03 '14 at 00:34
  • What is the format of the String. Will it always be 2 numbers added together? The pattern is of utmost importance, and your question is lacking in these important details. Please assume that we have no idea about the details of what you're trying to do. – Hovercraft Full Of Eels Feb 03 '14 at 00:36
  • The second number could be anything. I just wanted to show the format of the string. But I found the solution. String.split(" ") method did the job for me. Thank you all for your answers! – gozluklu_marti Feb 03 '14 at 17:10

3 Answers3

0

To extract all numbers reliably use regex. See this answer for example: How to extract numbers from a string and get an array of ints? or Extract number from string using regex in java, etc.

Community
  • 1
  • 1
yǝsʞǝla
  • 16,272
  • 2
  • 44
  • 65
0

You could do something like this, using a Scanner and a StringReader

String temp = "120.6 + 220.4";
java.io.StringReader sr = new java.io.StringReader(temp);
java.util.Scanner scanner = new java.util.Scanner(sr);
double d = -1;
while (scanner.hasNext()) {
  if (scanner.hasNextDouble()) {
    d = scanner.nextDouble();
    System.out.println(d);
  } else {
    scanner.next();
  }
}

Outputs

120.6
220.4

And the value of d will be 220.4 (as requested).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Look into regex. However, the solution to your problem is very simple:

String temp = "120.6 + 220.4";

String s = temp.split("\\+")[1]; // split by "+" and then take the second element

double d = Double.parseDouble(s.trim()); // parse the trimmed string to double

System.out.print(d);

Output:

220.4
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97