Add a space between each character

1

I try to separate the characters of a String by spaces using a regular expression. That is, 111 results 1 1 1 or ABC results A B C and the output should be a string.

String nombre = "111";
nombre = nombre.replaceAll("\ˆ\w\s", nombre);

Expected result: "1 1 1" ;

    
asked by Gdaimon 25.03.2018 в 16:17
source

1 answer

5

Replacing in the positions that are neither the beginning nor the end of the text:

texto = texto.replaceAll("(?!^|$)", " ");


Or, without regex (eliminating any space you have at the beginning / end):

texto = texto.replace("", " ").trim();


Or, leading to the generalized form to separate each N characters:

final int cadaN = 2;
final String separarCon = " ";

String texto = "probando!";

texto = texto.replaceAll("(?s).{" + cadaN + "}(?!$)", "$0" + separarCon);


System.out.println(texto);
pr ob an do !
  • since it matches the N characters, provided that it is not followed by the end of the text (?!$) , and replaces it so it coincided $0 followed by the space. The (?s) mode is so you can also match line breaks, if any.
answered by 25.03.2018 / 17:05
source