Invert characters of a String

2

I have a code that I made to invert a String, but it does not match what I need. I need it to convert the order of the characters of each sentence.

For example: It converts "Hi everyone!" in "real life". And what I need is for him to turn into "iO!".

My code:

public class ex1 {
        public static void main(String[] args) {
            String palavra = "Abobora Vermelha";
            String resultado=""; 

            for(int x = palavra.length() -1;x>=0;x--){
                resultado = resultado + palavra.charAt(x);
            }
            System.out.println(resultado);
        }
    }
    
asked by anonymous 14.06.2018 / 19:39

1 answer

3

First, the variable palavra actually contains a phrase. So, do not make things confusing, let's call it entrada .

You can use entrada.split(" ") to divide the input into the constituent words and then use its algorithm to invert them one by one. I also recommend using a StringBuilder to avoid creating a bunch of% s of intermediate% s that will be discarded by the garbage collector and thus cause a relatively poor performance.

Your code looks like this:

public class Ex1 {
    public static void main(String[] args) {
        String entrada = "Abobora Vermelha";
        StringBuilder resultado = new StringBuilder(entrada.length());

        for (String s : entrada.split(" ")) {
            if (resultado.length() != 0) resultado.append(' ');
            for (int x = s.length() - 1; x >= 0; x--) {
                resultado.append(s.charAt(x));
            }
        }
        System.out.println(resultado);
    }
}

See here working on ideone.

    
14.06.2018 / 19:54