我正在尝试实现用于计算字符串中数字的数量的算法,该算法分别包含正整数,负整数,正浮点数和负浮点数。
字符串是这样的:: String mystring =" -7.5,-1.43,3.4,43.5,-9954.88,949.5,1,3,-45&#34 ;;
我能够实现计算正负整数的代码,例如
当我运行此代码时,计数结果为15而不是3.任何人都可以帮助我如何实现逻辑以忽略正负浮点数???
感谢。
答案 0 :(得分:0)
如果要实现此算法,可以尝试以下方法:
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