user2979612
user2979612

Reputation: 177

Java .split - remove the first occurrence

How do I use .split() so that the first occurrence of the regex is also removed?

Example:

String a = "   a       b  cdef  g "
a.split("\\s+");

Gives me:

{"", "a", "b", "cdef", "g"}

Is there a way to remove the first element ("") without doing it separately? And why does this happen?

Upvotes: 2

Views: 1166

Answers (1)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Well... you can trim the String before splitting:

 a.trim().split("\\s+");

This will give you {"a", "b", "cdef", "g"}

Upvotes: 2

Related Questions