Java遍历字符串0字符及去除整数末尾零的代码问题排查
问题解答
1. 遍历字符串中所有'0'字符
有几种实用的实现方式:
方式一:普通for循环逐个遍历
String str = "abc0def0gh0"; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c == '0') { // 这里处理找到的'0',比如打印索引或字符 System.out.println("找到'0',索引:" + i); } }
方式二:增强for循环遍历字符数组
String str = "abc0def0gh0"; for (char c : str.toCharArray()) { if (c == '0') { System.out.println("找到'0'字符"); } }
方式三:Java 8 Stream流处理
String str = "abc0def0gh0"; str.chars() .mapToObj(c -> (char) c) .filter(c -> c == '0') .forEach(c -> System.out.println("找到'0'字符"));
2. 修复去除整数末尾零的Java代码
你的代码存在几个关键问题,逐个解决:
问题分析
- String不可变特性:
replaceAll会返回新字符串,不会修改原变量,必须把返回值重新赋值给sb,否则sb永远不变。 - 错误的替换逻辑:
replaceAll("0", " ")是把所有'0'换成空格,不是去掉末尾的'0',完全不符合需求。 - 空字符串解析异常:
Y始终是空值,最后Integer.parseInt(Y)会直接抛出NumberFormatException。 - 参数类型错误:
int最大值仅为2147483647,存不下20!(2432902008176640000)这类大数,参数应改用BigInteger或字符串。 - 方法名与逻辑不符:方法名
numTrailingZeros像是统计末尾零的数量,但代码逻辑是要去除末尾零,得先明确需求。
修正后的代码(去除末尾零,返回BigInteger)
如果需求是去除末尾零且保留大数(避免溢出),可以这样写:
import java.math.BigInteger; public class TrailingZeroHandler { public static BigInteger removeTrailingZeros(BigInteger num) { // 数字大于0且末尾为0时,不断除以10 while (num.compareTo(BigInteger.ZERO) > 0 && num.mod(BigInteger.TEN).equals(BigInteger.ZERO)) { num = num.divide(BigInteger.TEN); } return num; } public static void main(String[] args) { // 示例:20!的BigInteger值 BigInteger twentyFactorial = new BigInteger("2432902008176640000"); BigInteger result = removeTrailingZeros(twentyFactorial); System.out.println(result); // 输出:243290200817664 } }
若需求是统计末尾零的数量
可以修改代码如下:
import java.math.BigInteger; public class TrailingZeroCounter { public static int numTrailingZeros(BigInteger num) { int count = 0; while (num.compareTo(BigInteger.ZERO) > 0 && num.mod(BigInteger.TEN).equals(BigInteger.ZERO)) { count++; num = num.divide(BigInteger.TEN); } return count; } public static void main(String[] args) { BigInteger twentyFactorial = new BigInteger("2432902008176640000"); int count = numTrailingZeros(twentyFactorial); System.out.println(count); // 输出:4 } }
补充:处理科学计数法输入
如果输入是类似"2.432902e+18"的科学计数法字符串,需先转换为BigInteger:
String scientificStr = "2.432902e+18"; BigInteger num = new BigDecimal(scientificStr).toBigInteger();
内容的提问来源于stack exchange,提问作者Nutnicha
相关产品推荐
相关产品推荐

