本文介绍了删除阵列全部为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

  [0,5,6,0,0,2,5]

我想从中删除全部为零,使这一回报(保持相同的顺序排列):

  [5,6,2,5]

有去除比下面全零的更简单的方法?

  INT []数组= {0,5,6,0,0,2,5};
        INT LEN = 0;
        的for(int i = 0; I< array.length,我++){
            如果(阵列[I]!= 0)
                LEN ++;
        }
        INT [] newArray =新INT [LEN]
        的for(int i = 0,J = 0; I< array.length,我++){
            如果(阵列[I]!= 0){
                newArray [J] =阵列[我]
                J ++;
            }
        }

我一直没能找到在Arrays类的任何方法,和谷歌/ SO搜索没有给我任何好的答案。


解决方案

  INT J = 0;
    的for(int i = 0; I< array.length,我++)
    {
        如果(阵列[I]!= 0)
            数组[J ++] =阵列[我]
    }
    INT [] newArray = INT新[J]。
    System.arraycopy(阵列,0,newArray,0,j)的;
    返回newArray;

I have an array:

[0, 5, 6, 0, 0, 2, 5]

I would like to remove all zeros from it, so that this returns (keeping the same order):

[5, 6, 2, 5]

Is there any easier way to remove all zeros than the following?

int[] array = {0, 5, 6, 0, 0, 2, 5};
        int len = 0;
        for (int i=0; i<array.length; i++){
            if (array[i] != 0)
                len++;
        }
        int [] newArray = new int[len];
        for (int i=0, j=0; i<array.length; i++){
            if (array[i] != 0) {
                newArray[j] = array[i];
                j++;
            }
        }

I haven't been able to find any method in the Arrays class, and Google/SO searches didn't give me any good answers.

解决方案
    int j = 0;
    for( int i=0;  i<array.length;  i++ )
    {
        if (array[i] != 0)
            array[j++] = array[i];
    }
    int [] newArray = new int[j];
    System.arraycopy( array, 0, newArray, 0, j );
    return newArray;

这篇关于删除阵列全部为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 20:17