可以使用 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/mu0W 著作权归作者所有。请勿转载和采集!

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