2

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"]
A. Larsson
  • 1,319
  • 11
  • 16

3 Answers3

2

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

So one solution is:

row.replaceAll("^\\.+|\\.+$", "").split("\\.+");
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Actually, you don't get the same issue with trailing dots. Presumably becuase the final delimiter gets treated as marking the end of the fields, rather than the start of another field. Without the + you'd get empty fields at the end, but with it, you only need to strip leading delimiters. – michjnich May 24 '18 at 10:28
1

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

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

Output will be

["O","O","O"]
Danila Zharenkov
  • 1,720
  • 1
  • 15
  • 27
1

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?

michjnich
  • 2,796
  • 3
  • 15
  • 31