tags:

views:

114

answers:

6

Suppose you have a String[] that has been created after a .split() which then causes you to have a bunch of empty strings in there i.e.

myArray['','hello','thetimes','economist','','','hi']

Is there a way to remove them from the String[] without having to loop round, detecting if string is empty then adding to new array?

+5  A: 

There is an easier way here.

String.split("\\s+") will eliminate those empty strings.

danben
You can't invoke `.split()` on a `String[]`. I've already split my array on a certain string, for example `String[] hello = someString.split('abc');`, I can't then do a `.split()` on `hello[]`. Or.. perhaps I'm misunderstanding you?
day_trader
@theEconomist: No, you invoke `.split()` on the `String` itself. The regex parameter indicates the pattern to split around. That particular pattern I named matches "one or more whitespace characters", this eliminating the empty `String`s in the resulting array.
danben
@theEconomist: Also, if you are splitting around more than whitespace, you can expand your regex to include surrounding whitespace. For example, `someString.split('abc')` would become `someString.split(\\s*abc\\s*)`.
danben
+3  A: 

Is there a way to remove them from the String[] without having to loop round, detecting if string is empty then adding to new array?

No. Arrays have a fixed length.

Michael Borgwardt
A: 

It's probably simplest to convert it to a List, iterate over that and remove the empty elements, e.g.

List<String> parts = new LinkedList<String>(string.split(pattern));
for (Iterator<String> it = parts.iterator();
     it.hasNext();
     ) {
    if (it.next().isEmpty()) {
        it.remove();
    }
}
return parts.toArray(new String[parts.size()]);
finnw
There will be no empty string after the split!
fastcodejava
A: 
String[] parts = string.split("\\s*" + splitString + "\\s*");

Where splitString is the string on which you were originally splitting.

This extends the split string adding any number of whitespaces to it, so that they are realized as part of the splitter, not part of the resulting array.

Bozho
A: 

The real problem is in your regex string which is doing the split. Have a look here for a list of special notations to add like others have been suggesting, such as \\s.

If you want to go the easier route than learning regex, you could just iterate through the array and add each non-empty String to an ArrayList<String> and then change it back to a fixed size array.

Kavon Farvardin
A: 

There is no simple method to remove elements from an array. You can do replaceAll() and then call split or call split("\\s+") with multiple space.

fastcodejava