我正在尝试实现计算字符串中分别包含正整数、负整数、正 float 和负 float 的数字数量的算法。
字符串是这样的:: 字符串mystring =“-7.5,-1.43,3.4,43.5,-9954.88,949.5,1,3,-45”;
我能够实现计算正整数和负整数的代码,例如
当我运行这段代码时,计数结果是 15 而不是 3。任何人都可以帮助我如何实现忽略正 float 和负 float 的逻辑吗???
谢谢。
最佳答案
如果你想实现这个算法,你可以尝试这样的事情:
public static int countIntegers(String input) {
int count = 0;
boolean sequenceStarted = false;
boolean isInteger = false;
boolean tailSpace = false;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c == ',') {
//we got a delimiter; checking that the previous sequence is an integer
if (sequenceStarted && (isInteger || tailSpace)) count++;
sequenceStarted = false;
isInteger = false;
tailSpace = false;
} else if (!sequenceStarted && c != ' ') {
//ignoring all leading spaces
sequenceStarted = true;
//we got a digit, + or -; it means that number is started
if (Character.isDigit(c) || (c == '+' || c == '-')
&& Character.isDigit(input.charAt(i + 1)))
isInteger = true;
} else if (sequenceStarted && !Character.isDigit(c)) {
//the character is not a digit, but maybe it is a tail space?
tailSpace = (isInteger || tailSpace) && c == ' ';
isInteger = false;
}
}
return count;
}
此代码考虑了前导空格和尾随空格,并且仅计算整数。例如,对于给定字符串 String mystring = ", 4 ,+-7, ,-,-7.5,-1.43,3.4,43.5, -9954.88 , r949, 1, 3, -45, 0.0, 5s, 7-, 2+2";
它将打印 4
。
当然,如果您只想计算字符串中可能仅包含数字、空格、点和逗号的所有整数,那么 Java 8 解决方案就是您所需要的:
String mystring = "-7.5,-1.43,3.4,43.5, -9954.88, 949.5, 1, 3, -45";
long count =
// splitting your string by ","
Arrays.stream(mystring.split(","))
// converting each string to double
.map(Double::parseDouble)
// leaving only integers: if d is equal to Math.floor(d) then it must have an int value
.filter(d -> Math.floor(d) == d && d != 0)
.count();
System.out.println(count); //prints 3
关于java - 计算字符串中逗号分隔的正数和负数的总出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48434140/