如何从 Java 中的字符串解析整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9935352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:57:28  来源:igfitidea点击:

How can I parse integers from a string in Java?

javastringparsing

提问by Rocky

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

我需要从一个字符串中将分母和分母检索到两个 int 类型变量中。它可能是:“1/-2”、“4/0”、“-2/ 1234”或“5”(在这种情况下,分母为 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 = s.trim();

s = s.trim();

String[] tokens = s.split("[ /]+");

String[] tokens = s.split("[ /]+");

int inputNumerator = Integer.parseInt(tokens[0]);

int inputNumerator = Integer.parseInt(tokens[0]);

int inputDenominator = 1;

int inputDenominator = 1;

if (tokens.length != 1)

if (tokens.length != 1)

      `inputDenominator = Integer.parseInt(tokens[1]);`

回答by Daniel Lubarov

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

回答by Rocky

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.

使用“/”作为分隔符分隔字符串,然后删除所有空格。之后使用Integer.parseInt();
要删除空格,您可以尝试检查第一个字符串的最后一个和第二个字符串的第一个字符,将它们与“ ”进行比较,如果匹配删除它们。

回答by Mohankumar Dhayalan

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