Rocky
Rocky

Reputation: 63

How can I parse integers from a string in Java?

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]);

Upvotes: 4

Views: 12118

Answers (4)

Mohankumar Dhayalan
Mohankumar Dhayalan

Reputation: 46

Hope this helps..,

StringTokenizer st= new StringTokenizer(s, "/");   
int inputDenominator,inputNumerator;

if(st.hasMoreTokens()) 
{
String string1= st.nextToken();
string1=string1.trim();
inputNumerator = Integer.parseInt(string1);
}

if(st.hasMoreTokens()) 
{
String string2= st.nextToken();
string2=string2.trim();
inputDenominator = Integer.parseInt(string2);
} 
else{
inputDenominator=1; 
}

Upvotes: 0

Daniel Lubarov
Daniel Lubarov

Reputation: 7924

String[] parts = s.split(" */ *");
int num = Integer.parseInt(parts[0]),
    den = Integer.parseInt(parts[1]);

Upvotes: 7

arvind_cool
arvind_cool

Reputation: 293

Take a look at this

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html

hope it helps!

Upvotes: 0

user1241335
user1241335

Reputation:

Separate the string using '/' as a delimiter, then remove all spaces. After that use Integer.parseInt();
To remove spaces well, you can try and check for the last of the 1st string and the 1st char of the 2nd string, compare them to ' ', if match remove them.

Upvotes: 3

Related Questions