Splitter.on(' ').limit(4).split(input);
This uses Guava and your processor will be happy to not have to deal with the regular expressions, unlike input.split("\\s", 4)
.
If you need a broader space matching, you can use
Splitter.on(CharMatcher.WHITESPACE).limit(4).split(input);
Or you can create your own CharMatcher
, of course.
But what I'd really do is define the Splitter
in my class (static) or instance (non static) and then use split
on it. So you only have to define it once and it will be ready for each call you make!
class MyClass {
static Splitter splitter = Splitter.on(CharMatcher.WHITESPACE).limit(4);
...
Iterable<String> slices = splitter.split(input);
}