6

I want to eliminate empty elements within my String array. 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.

8
  • You sure there's no whitespace in them? Commented Mar 25, 2012 at 8:41
  • 2
    BTW, you do realize that any time you don't copy a string, you're leaving a null at xml[i], right? One of the consequences of using the same index for both arrays... Commented Mar 25, 2012 at 8:43
  • Are you certain they are empty (and not just strings containing solely whitespace characters)? Perhaps try trimming (str[i].trim()) before performing the comparison? Note that == is not what you want here, but either of the other two should work. Commented Mar 25, 2012 at 8:43
  • yea... i'm pretty sure... i'll post an image.. Commented Mar 25, 2012 at 8:43
  • 1
    @BlueMonster: if you're copying into an array, you don't -- because you're copying fewer elements into the same size array, there will pretty much always be nulls in there, unless you go through once and count how many strings aren't empty and then make xml that size before you copy. (If you do that, you can have another int that's the index into xml, and bump that whenever you copy a string.) But far better would be to use an ArrayList, as mentioned below. Commented Mar 25, 2012 at 8:48

6 Answers 6

14

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Although this code may help to solve the problem, it doesn't explain why and/or how it answers the question. Providing this additional context would significantly improve its long-term educational value. Please edit your answer to add explanation, including what limitations and assumptions apply.
9

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

2 Comments

hmm, i'm using a String array, not a List of Strings.. thanks anyway
hmm, added a line to convert one to the other. ;)
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);
    }

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

Comments

0

This is just an alternate solution since you didn't want 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. If you are comfortable with it,carry on! :D

Comments

0

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.

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.

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<

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.