复制字符串数组并移除空字符串

6

我想要去除我的String数组中的空元素。目前我已经尝试过以下方法:

String version = null; 
String[] xml = new String[str.length]; 
for(int i = 0; i <= str.length -1; i++)
{
    if(str[i] == "")
    {

    }
    else
    {
        xml[i] = str[i]; 
    }
}

String version = null; 
String[] xml = new String[str.length]; 
for(int i = 0; i <= str.length -1; i++)
{
    if(!str[i].equals(""))
    {
        xml[i] = str[i]; 
    }
}

String version = null; 
String[] xml = new String[str.length]; 
for(int i = 0; i <= str.length -1; i++)
{
    if(!str[i].isEmpty())
    {
        xml[i] = str[i]; 
    }
}

String version = null; 
String[] xml = new String[str.length]; 
for(int i = 0; i <= str.length -1; i++)
{
    if(str[i].isEmpty() == false)
    {
        xml[i] = str[i]; 
    }
}

无论我尝试哪个方法,它总是复制所有的值。我已经检查过局部变量,很明显在 String 数组中有空数组。

2
顺便提一下,您应该意识到每当您不复制一个字符串时,就会在 xml[i] 上留下一个 null,对吧?这是同时使用两个数组的相同索引的后果之一... - cHao
你确定它们是空的(而不仅仅是包含空格字符的字符串)吗?也许在比较之前尝试修剪(str[i].trim())?请注意,== 在这里不是你想要的,但其他两个应该可以。 - Jon Newmuis
是的...我相当确定...我会发布一张图片.. - BigBug
1
@BlueMonster:如果你正在将内容复制到一个数组中,那么你不需要这样做--因为你在将较少的元素复制到相同大小的数组中时,里面几乎总会有空值,除非你先遍历一遍并计算出有多少个字符串不为空,然后在复制之前将xml的大小设置为该值。(如果你这样做了,你可以再定义一个int类型的变量作为xml的索引,并在每次复制字符串时将其递增。)但更好的方法是使用ArrayList,如下所述。 - cHao
谢谢 :) 我现在明白了。这真的很有趣。即使我在得到正确的数组后复制,它仍然会将空格放入我要复制到的数组中(我猜是因为长度),这是一个组合体和""和null。有趣! - BigBug
显示剩余3条评论
6个回答

14
尝试这个。
b = Arrays.copyOf(a, a.length);
或者
b = new int[a.length];
System.arraycopy(a, 0, b, 0, b.length);

或者

b = a.clone();

1
尽管这段代码可能有助于解决问题,但它并没有解释为什么以及如何回答这个问题。提供这种额外的上下文将显著提高其长期教育价值。请编辑您的答案以添加说明,包括适用的限制和假设。 - Toby Speight

9
您正在复制相同长度的数组并使用相同的索引。长度将始终相同。
List<String> nonBlank = new ArrayList<String>();
for(String s: str) {
    if (!s.trim().isEmpty()) {
        nonBlank.add(s);
    }
}
// nonBlank will have all the elements which contain some characters.
String[] strArr = (String[]) nonBlank.toArray( new String[nonBlank.size()] );

嗯,我正在使用一个字符串数组,而不是字符串列表.. 不过还是谢谢。 - BigBug
嗯,添加了一行代码将一个转换为另一个。 ;) - Peter Lawrey

0
String str[] = {"Hello","Hi","","","Happy","","Hmm"};
    int count = 0;// Thisreprents the number of empty strings in the array str
    String[] xml = new String[str.length]; 
    for(int i = 0,j=0; i <= str.length -1; i++)
    {
        if(str[i].equals(""))
        {
            count++;
        }
        else
        {
            xml[j] = str[i];j++; 
        }
    }
    String a[] = Arrays.copyOfRange(xml, 0, xml.length-count);//s is the target array made by copieng the non-null values of xml
    for(String s:a){
        System.out.println(s);
    }

注意:这可能不是一种高效的解决方案,但它将按照您的要求给出结果。


0
这只是一个替代方案,因为您不想要 ListArray。请阅读代码中的注释,以清楚地理解逻辑。
int i,j=0,cnt=0;

//The below for loop is used to calculate the length of the xml array which
//shouldn't have any empty strings.

for(i=0;i<str.length;i++)
if(!isEmpty(str[i])
cnt++;

//Creation of the xml array with proper size(cnt) and initialising i=0 for further use
String xml[]=new String[cnt];
i=0;

//Simply copying into the xml array if str[i] is not empty.Notice xml[j] not xml[i]
while(i<str.length)
{
if(!isEmpty(str[i]))
{
xml[j]=str[i];
i++;
j++;
}
else
i++;
}

应该可以完成工作。 此外,我建议不要使用数组的第0个位置,因为这会对 .length 函数造成困惑。这只是我的看法。如果你感到舒适,继续吧!:D


0
如果您正在寻找高性能的解决方案,我认为这是最好的解决方案。否则,如果您的输入数组不是很大,我会使用类似Peter Lawrey的解决方案,这样可以使您的代码易于理解。
使用此解决方案,您只需循环一次输入数组,如果您不再需要输入数组,则可以通过调用filterBlankLines并将preserveInput = false避免一个数组副本。
public class CopyingStringArrayIntoNewStringArray {


public static void main(String[] args) {

    String[] str =  { "", "1", "", null, "2", "   ", "3", "" };

    System.out.println("\nBefore:");
    printArrays(str);

    String[] xml = filterBlankLines(str, true);

    System.out.println("\nAfter:");
    printArrays(xml);

}

private static String[] filterBlankLines(String input[], boolean preserveInput ) {

    String[] str;
    if (preserveInput) {
        str = new String[input.length];
        System.arraycopy(input, 0, str, 0, input.length);
    } else {
        str = input;
    }

    // Filter values null, empty or with blank spaces
    int p=0, i=0;
    for (; i < str.length; i++, p++) {
        str[p] = str[i];
        if (str[i] == null || str[i].isEmpty() || (str[i].startsWith(" ") && str[i].trim().isEmpty())) p--;
    }

    // Resize the array
    String[] tmp = new String[ p ];
    System.arraycopy(str, 0, tmp, 0, p);
    str = null;

    return tmp;
}

private static void printArrays(String str[]) {

    System.out.println( "length " + str.length);
    for (String s : str ) {
        System.out.println(">"+s+"<");
    }

}

}

输出:

Before:
length 8
><
>1<
><
>null<
>2<
>   <
>3<
><

After:
length 3
>1<
>2<
>3<

0

这是将数组复制到新数组的最佳且简短的方法。

System.arraycopy(srcArray, 0, destArray, 1, destArray.length -1);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接