Java 复制字符串数组并删除空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9858865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 12:23:41  来源:igfitidea点击:

Copy String array and remove empty strings

javaarraysstring

提问by BigBug

I want to eliminate empty elements within my Stringarray. This is what I have tried so far:

我想消除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]; 
    }
}

No matter which one I try, it always copies all the values. I've checked the locals, and it is clear that there are empty arrays within the Stringarray.

无论我尝试哪一种,它总是复制所有值。我检查了当地人,很明显数组中有空String数组。

采纳答案by Peter Lawrey

You are copying the same length array and using the same indexes. The length is always going to be the same.

您正在复制相同长度的数组并使用相同的索引。长度总是一样的。

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()] );

回答by Chandra Sekhar

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);
    }

NOTE :This may not be an efficient solution but it will give the result as per your requirement

注意:这可能不是一个有效的解决方案,但它会根据您的要求给出结果

回答by Exorcist

This is just an alternate solution since you didn't want ListArray. Read the comments in the code to clearly understand the logic.

这只是一个替代解决方案,因为您不想要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++;
}

That should do the work. Also I would suggest to not work with the 0th position of array as it kinda creates confusion for .lengthfunctions.Thats only my view. If you are comfortable with it,carry on! :D

那应该做的工作。此外,我建议不要使用数组的第 0 个位置,因为它会造成.length函数混淆。这只是我的看法。如果您对此感到满意,请继续!:D

回答by jordeu

If you are looking for a high-performance solution I think that this is the best solution. Otherwise if your input array is not so huge, I would use a solution similar to Peter Lawrey one, so it makes your code easy to understand.

如果您正在寻找高性能解决方案,我认为这是最好的解决方案。否则,如果您的输入数组不是很大,我会使用类似于 Peter Lawrey 的解决方案,这样您的代码就易于理解。

With this solution you loop the input array only one, and if you don't need the input array any more you can avoid one array copy calling filterBlankLines with preserveInput = false.

使用此解决方案,您只循环输入数组一个,如果您不再需要输入数组,则可以避免使用保留输入 = false 调用 filterBlankLines 的一个数组副本。

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+"<");
    }

}

}

}

The output:

输出:

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

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

回答by Shahzadah Babu

Try this,

尝试这个,

b = Arrays.copyOf(a, a.length);

Or

或者

b = new int[a.length];
System.arraycopy(a, 0, b, 0, b.length);

Or

或者

b = a.clone();

回答by Muhammad Asim

This is the best and short way to copy an array into the new array.

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

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