A. Backhagen
A. Backhagen

Reputation: 1407

Splitting string in java produces empty element first

Im trying to split a sting on multiple or single occurences of "O" and all other characters will be dots. I'm wondering why this produces en empty string first.

String row = ".....O.O.O"
String[] arr = row.split("\\.+");

This produces produces:

["", "O", "O", "O"]

Upvotes: 2

Views: 125

Answers (3)

Sweeper
Sweeper

Reputation: 271150

You just need to make sure that any trailing or leading dots are removed.

So one solution is:

row.replaceAll("^\\.+|\\.+$", "").split("\\.+");

Upvotes: 2

michjnich
michjnich

Reputation: 3385

The "+" character is removing multiple instances of the seperator, so what your split is essentially doing is splitting the following string on "."

.0.0.0.

This, of course, means that your first field is empty. Hence the result you get.

To avoid this, strip all leading separators from the string before splitting it. Rather than type some examples on how to do this, here's a thread with a few suggestions.

Java - Trim leading or trailing characters from a string?

Upvotes: 1

Danila Zharenkov
Danila Zharenkov

Reputation: 1863

For this pattern you can use replaceFirstMethod() and then split by dot

String[] arr = row.replaceFirst("\\.+","").split("\\.");

Output will be

["O","O","O"]

Upvotes: 1

Related Questions