How can I parse integers from a string in Java?
11,436
String[] parts = s.split(" */ *");
int num = Integer.parseInt(parts[0]),
den = Integer.parseInt(parts[1]);
Author by
Rocky
Updated on June 23, 2022Comments
-
Rocky almost 2 years
I need to retrieve out the nominator and denominator into two int type variables, from a string. It could be: "1/-2", "4 /0", "-2/ 1234", or " 5"(in this case the denominator is 1);
There might be spaces between the integers and "/", no spaces inside a integer. And there might be only one integer in the string and no "/".
Any ideas? Thanks.
Hi, I combined your guys' answers, and it works! Thanks!
s is the string
s = s.trim(); String[] tokens = s.split("[ /]+"); int inputNumerator = Integer.parseInt(tokens[0]); int inputDenominator = 1; if (tokens.length != 1) inputDenominator = Integer.parseInt(tokens[1]);