In JavaScript this is how we can split a string at every 3-rd character
"foobarspam".match(/.{1,3}/g)
I am trying to figure out how to do this in Java. Any pointers?
In JavaScript this is how we can split a string at every 3-rd character
"foobarspam".match(/.{1,3}/g)
I am trying to figure out how to do this in Java. Any pointers?
You could do it like this:
which produces:
The regex
(?<=\G...)
matches an empty string that has the last match (\G
) followed by three characters (...
) before it ((?<= )
)Java does not provide very full-featured splitting utilities, so the Guava libraries do:
Check out the Javadoc for Splitter; it's very powerful.
This a late answer, but I am putting it out there anyway for any new programmers to see:
If you do not want to use regular expressions, and do not wish to rely on a third party library, you can use this method instead, which takes between 89920 and 100113 nanoseconds in a 2.80 GHz CPU (less than a millisecond). It's not as pretty as Simon Nickerson's example, but it works:
As an addition to Bart Kiers answer I want to add that it is possible instead of using the three dots
...
in the regex expression which are representing three characters you can write.{3}
which has the same meaning.Then the code would look like the following:
With this it would be easier to modify the string length and the creation of a function is now reasonable with a variable input string length. This could be done look like the following:
An example in IdeOne: http://ideone.com/rNlTj5
Late Entry.
Following is a succinct implementation using Java8 streams, a one liner:
Output: