Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy String array and remove empty strings

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.

like image 595
BigBug Avatar asked Mar 25 '12 08:03

BigBug


2 Answers

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();
like image 66
Shahzadah Babu Avatar answered Sep 21 '22 02:09

Shahzadah Babu


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()] );
like image 32
Peter Lawrey Avatar answered Sep 22 '22 02:09

Peter Lawrey