我需要从字符串中将分母和分母检索到两个 int 类型变量中。它可能是: "1/-2"、"4/0"、"-2/1234"或 "5"(此时分母为 1);
整数和“/”之间可以有空格,整数内部不能有空格。 并且字符串中可能只有一个整数,没有“/”。
有什么想法吗?谢谢。
嗨,我结合了你们的答案,它有效!谢谢!
s 是字符串
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]);
关于java - 如何在 Java 中解析字符串中的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9935352/