Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string after each two characters [duplicate]

Tags:

java

string

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 :)

like image 819
lisa Avatar asked Nov 29 '22 08:11

lisa


2 Answers

Use regex:

        String str= "abcdef";

        String[] array=str.split("(?<=\\G.{2})");

        System.out.println(java.util.Arrays.toString(array));       

Output:

[ab, cd, ef]

like image 193
Ankur Lathi Avatar answered Dec 04 '22 15:12

Ankur Lathi


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 "
like image 38
anubhava Avatar answered Dec 04 '22 16:12

anubhava