可以使用Java中的正则表达式来匹配字符串中的数字,然后统计个数。具体代码如下:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CountNumber {
    public static void main(String[] args) {
        String str = "abc123def456";
        int count = countNumber(str);
        System.out.println("数字个数:" + count);
    }

    public static int countNumber(String str) {
        Pattern pattern = Pattern.compile("\\d"); // 匹配数字的正则表达式
        Matcher matcher = pattern.matcher(str);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        return count;
    }
}

运行结果为:

数字个数:6
JAVA中输入一个字符串查找该字符串中数字的个数

原文地址: https://www.cveoy.top/t/topic/6Q7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录