简体   繁体   English

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

[英]Copy String array and remove empty strings

I want to eliminate empty elements within my String array.我想消除我的String数组中的空元素。 This is what I have tried so far:这是我迄今为止尝试过的:

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 String array.我检查了locals,很明显String数组中有空数组。

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

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

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

System.arraycopy(srcArray, 0, destArray, 1, destArray.length -1);
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注意:这可能不是一个有效的解决方案,但它会根据您的要求给出结果

This is just an alternate solution since you didn't want ListArray .这只是一个替代解决方案,因为您不想要ListArray Read the comments in the code to clearly understand the logic.阅读代码中的注释可以清楚地理解其中的逻辑。

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 .length functions.Thats only my view.此外,我建议不要使用数组的第 0 个位置,因为它会造成.length函数的混乱。这只是我的看法。 If you are comfortable with it,carry on!如果您对此感到满意,请继续! :D :D

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<

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM