java 将字符串转换为int并删除尾随零

标签 java string arraylist int zero

大家好,我目前正在尝试将字符串反向转换为 arrayList,然后删除所有尾随零 例如“001203”转换为(3,0.2,1,0,0),然后转换为(3,0,2,1)

我的代码目前是

public convert(String nums) {
    List = new ArrayList<Integer>();  // create arraylist

    for (int i = nums.length(); i >= 0; i--) { //convert to int
        int j = Integer.parseInt(digits);
        List .add(j);

        for (Iterator<Integer> k = List .iterator(); k.hasNext();) {  //remove trailing zeros
            if (k.next().equals(0)) {
                k.remove();
            }
        }

    }

此代码当前删除所有 0,而不是尾随零。这意味着我的输出是 (3,2,1) 而不是 (3,0,2,1);

任何帮助将不胜感激 提前致谢

最佳答案

您的方法的问题在于,在内部循环中,无论零在列表中的位置如何,您都会删除零。

有多种方法可以实现您想要的目标。这是一种使用单个循环的方法(没有为您反转列表的字符串或集合操作):

    String nums = "001203";

    List<Integer> list = new ArrayList<>();

    // a boolean flag to help check for leading zeroes
    // set it to true first i.e. assume there are leading zeroes
    boolean checkLeadingZeroes = true;

    // Ignore leading zeroes during iteration,
    // and append to list in reverse order

    for (int i=0; i < nums.length(); i++){
        int n = Integer.parseInt(nums.charAt(i)+"");

        // only check for leading zeroes if flag is true

        if (checkLeadingZeroes){
            // If flag is set to false here, you've found the first non-zero

            checkLeadingZeroes = (n == 0);
        }

        if (!checkLeadingZeroes) {
            /* If flag is false, n is not a leading zero
             * Add n to the beginning of your list (index 0)
             */
            list.add(0, n);
        }
    }

其他几个选项:

  1. 更改内部循环,以便在列表上向后迭代,并删除零,直到找到非零值

  2. 首先修剪所有前导零(例如使用正则表达式操作或循环),然后向后循环以创建列表。

希望有帮助。

关于java 将字符串转换为int并删除尾随零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30397998/

相关文章:

java - 将 GET 参数添加到 Play Framework 2.2 响应

javascript - 难倒 : IE8 Message: Expected identifier, 字符串或数字行:82 字符:1 代码:0

python - python中的n-gram,四,五,六克?

Android 将文本转换为位图(包括字体、颜色和大小)的最佳方法是什么?

java - Android 上的 JXTA 应用程序

java - 检查 2 个数组以查看它们是否具有相同的值?

java - 3 : Permission denied. 在 com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2846)

java - CSV 中的日期未按所需格式写入

java - Map 可以将 java 类 ByteArrayoutputstream 作为值吗? List 可以保存 javax.mail.MimeMessage 对象吗?

java - 从其他类中的ArrayList获取大小并比较属性值