Java:计算字符串中整数的数量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39823137/
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-11-03 04:40:00  来源:igfitidea点击:

Java: Count the number of integers in a string

javastringintegerdigit

提问by user3411748

I cant quite work out what i am doing wrong. I am trying to count the amount of digits in an inputted string but for example, if the number is 21 i want to count that as 1 inputted digit in the string.

我无法弄清楚我做错了什么。我正在尝试计算输入字符串中的数字数量,但例如,如果数字是 21,我想将其计为字符串中的 1 个输入数字。

So far i have the following but i can't work out how to count it as 1 integer rather than 2.

到目前为止,我有以下内容,但我不知道如何将它算作 1 个整数而不是 2 个。

public static int countIntegers(String input) { 
    int count = 0;
    for (int i = 0; i < input.length(); i++) {
        if (Character.isDigit(input.charAt(i))) {
            count++;
        }
    }
    return count;
}

My issue is I want it to a string because there is a certain format the string has to be inputted in.

我的问题是我想要一个字符串,因为必须输入某种格式的字符串。

回答by Edward Shen

You want to split the input, then check each substring is an int.

您想拆分输入,然后检查每个子字符串是否为 int。

public static int countIntegers(String input) {
    String[] parsed = input.split(","); // , is the delimiter
    int count = 0;
    for (String s : parsed) {
        if (s.trim().matches("^-?\d+$")) { // A slow regex method, but quick and dirty
            count++;
        }
    }

    return count;
}

Example input: home,21,car,30,bus,13

示例输入: home,21,car,30,bus,13

Output: 3

输出: 3

回答by Sergey Brunov

Basically, a number — a contiguous sequence of digits.
So, the idea of the algorithm is to count number of such sequences.

基本上,一个数字——一个连续的数字序列。
因此,该算法的思想是计算此类序列的数量。

I would like to propose the following implementation of the algorithm:

我想提出算法的以下实现:

public static int countIntegers(String input) {
    int count = 0;
    boolean isPreviousDigit = false;

    for (int i = 0; i < input.length(); i++) {
        if (Character.isDigit(input.charAt(i))) {
            if (!isPreviousDigit) {
                count++;
                isPreviousDigit = true;
            }
        } else {
            isPreviousDigit = false;
        }
    }
    return count;
}