Add spaces before uppercase

2

I have a String that has some text like the following:     "I am a Prayer"

What I want is to be able to add spaces before capital letters so that it looks like this: "I am A Prayer"

    
asked by gibran alexis moreno zuñiga 17.03.2017 в 01:38
source

2 answers

1

You can do it with a simple regex: which captures two groups in the variables $1 and $2 and separates them by a space, [A-Z] tells you to capture uppercase only.

DEMO

class Espacio
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String text="soyUnaOración";
        String sNuevo = text.replaceAll("(.)([A-Z])", "$1 $2");
        System.out.println(sNuevo);

    }
}

RESULT
  

soy Una Oración

    
answered by 17.03.2017 / 03:10
source
0

Hello, there may be several ways to achieve this, here is a simple example:

          String laCadena="unaOracionHola";
            StringBuffer nuevaCadena = new StringBuffer();
            for (int i=0;i<laCadena.length(); i++)
            {
               if (Character.isUpperCase(laCadena.charAt(i))) {
                  nuevaCadena.append(" ");
                  nuevaCadena.append(laCadena.toCharArray()[i]);
               } else {
                  nuevaCadena.append(laCadena.charAt(i));
               }
            }
            System.out.println(nuevaCadena);

Output: a Prayer Hello

    
answered by 17.03.2017 в 01:56