String.split () to separate in spaces, but without replacing spaces


I have a String like the following:

String foo = "soy un texto" 

When applying the following function:

String []  bar = foo. split(" ");

He separates it into three texts:

"soy", "un" y "texto" 

However, I want to keep the spaces like the following example:

"soy",  " un"  y " texto" 

How can I do that?

asked by gibran alexis moreno zuñiga 18.01.2017 в 19:24

3 answers


With the clarified specifications the regex that you can use in split is:

String foo = "Soy un texto";
String[] bar = foo.split("(?=\s)");
for (String foobar : bar ){
    System.out.println(String.format("<%s>", foobar));

(?=X) makes you a match of places followed by a space, without consuming characters.


< un>
< texto> 
answered by 18.01.2017 / 22:49

We can add an element that will serve as an identifier to make split for example:

String foo = "soy un texto";

foo = foo.replace(" ", "☺ ");//remplazamos por un caracter que no tenga la cadena
//y dejamos el espacio   ^ en blanco    
String []  bar = foo.split("☺");//y despues usamos el caracter

This gives

" un"
" texto"

If we want the space on the right we change our replace for .replace(" ", " -")

What would you give:

"soy "
"un "
answered by 18.01.2017 в 22:26

you can add it yourself after doing the split

for(int i = 0;i < bar.length; i++) {
    if(i != 0) { //para que no se lo agregue al primer split
        bar[i] = " " + bar[i];
answered by 18.01.2017 в 19:37