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.
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()] );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With