从Java中的String数组中删除未填充的值或空值 [英] Removing unfilled values or null values from array of String in Java

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

问题描述

执行此操作后,我有以下字符串数组
tmp = [null,null,null,Mars,Saturn,Mars] -
allSig [d3] .split(); 其中 allSig 是一个字符串数组。 null值是数组中的空值。现在我想删除null。为此,我正在使用

I have following String Array tmp = [null, null, null, Mars, Saturn, Mars] coming after doing the operation - allSig[d3].split(" "); where allSig is an array of Strings. The null value is empty value in the array. Now I want to remove the null. For this I am using

tmp [indexNumber]!= null 无法正常工作并给出真实;取null作为值。即使我使用null作为字符串不起作用。

tmp[indexNumber] != null is not working and giving true ; taking null as the value. Even if i am using "null" as a string is not working.

如何删除它。

public static String[] removeElements(String[] allElements) {
    String[] _localAllElements = new String[allElements.length];

    for (int i = 0; i < allElements.length; i++)
        if (allElements[i] != null)
            _localAllElements[i] = allElements[i];

    return _localAllElements;
}


推荐答案

public static String[] clean(final String[] v) {
  int r, w;
  final int n = r = w = v.length;
  while (r > 0) {
    final String s = v[--r];
    if (!s.equals("null")) {
      v[--w] = s;
    }
  }
  return Arrays.copyOfRange(v, w, n);
}

public static String[] clean(final String[] v) {
  int r, w, n = r = w = v.length;
  while (r > 0) {
    final String s = v[--r];
    if (!s.equals("null")) {
      v[--w] = s;
    }
  }
  final String[] c = new String[n -= w];
  System.arraycopy(v, w, c, 0, n);
  return c;
}

工作正常......

Works fine...

public static void main(final String[] argv) {
  final String[] source = new String[] { "Mars", "null", "Saturn", "null", "Mars" };
  assert Arrays.equals(clean(source), new String[] { "Mars", "Saturn", "Mars" });
}

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

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