Split a string after each two characters

14,126

Solution 1

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 "

Solution 2

Use regex:

        String str= "abcdef";

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

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

Output:

[ab, cd, ef]

Solution 3

If you want the output to be the same string with extra spaces, you can simply use:

String newString = aString.replaceAll("(..)", "$1 ")

Solution 4

try this

    String[] a = "abcdef".split("(?<=\\G..)");
    System.out.println(Arrays.asList(a));

output

[ab, cd, ef]

Solution 5

String aString= "abcdef";       
int partitionSize=2;
for (int i=0; i<aString.length(); i+=partitionSize)
{
    System.out.println(aString.substring(i, Math.min(aString.length(), i + partitionSize)));
}
Share:
14,126
lisa
Author by

lisa

Updated on July 22, 2022

Comments

  • lisa
    lisa almost 2 years

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