java: Deleting Element from Array after .split()
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[]
开发者_Python百科without having to loop round, detecting if string is empty then adding to new array?
There is an easier way here.
String.split("\\s+")
will eliminate those empty strings.
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.
Here is the right MAGIC way:
String str = "1, 2,3 4,, , ,5,,6, ,";
String arr[] = str.split("(\\s*,\\s*)+");
The solutions solve only a part of the problem - remove only the trailing empty strings. I used:
String st = "a,b,c,,d,,f,,,";
List<String> list = Arrays.asList(st.split("\\s*,\\s*"));
while (list.remove(""));
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.
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.
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()]);
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.
精彩评论