I want to split a string after each two characters.
For Example:
String aString= "abcdef"
I want to have after a split "ab cd ef"
How can i do it?
Thanks :)
Use regex:
String str= "abcdef";
String[] array=str.split("(?<=\\G.{2})");
System.out.println(java.util.Arrays.toString(array));
Output:
[ab, cd, ef]
This negative looakahead based regex should work for you:
String repl = "abcdef".replaceAll("..(?!$)", "$0 ");
PS: This will avoid appending space after last match, so you get this output:
"ab cd ef"
instead of:
"ab cd ef "
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With