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.