简体   繁体   中英

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]);`
String[] parts = s.split(" */ *");
int num = Integer.parseInt(parts[0]),
    den = Integer.parseInt(parts[1]);

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.

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; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM