从数组中删除所有零 [英] Remove all zeros from array

查看:25
本文介绍了从数组中删除所有零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

[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++;
            }
        }

我在 Arrays 类中找不到任何方法,而且 Google/SO 搜索也没有给我任何好的答案.

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

推荐答案

这是在代码中显示它比用简单的英语解释更容易的罕见情况之一:

This is one of those rare cases where it is easier to show it in code than to explain in plain English:

int targetIndex = 0;
for( int sourceIndex = 0;  sourceIndex < array.length;  sourceIndex++ )
{
    if( array[sourceIndex] != 0 )
        array[targetIndex++] = array[sourceIndex];
}
int[] newArray = new int[targetIndex];
System.arraycopy( array, 0, newArray, 0, targetIndex );
return newArray;

这篇关于从数组中删除所有零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆