Java 如何统计字符串中的数字
统计字符串中的数字
遍历每个字符,统计其中有多少个是数字(0-9)。
示例
String text = "W3Schools was founded in 1998";
int count = 0;
for (char c : text.toCharArray()) {
if (Character.isDigit(c)) {
count++;
}
}
System.out.println("Digits: " + count);
说明: 我们遍历字符串中的每个字符。Character.isDigit() 方法检查字符是否为数字。在上面的示例中,程序找到了 5 个数字。

