Invert characters from a String

Asked

Viewed 641 times

2

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

For example: He converts "Hi guys!" into "! laossep Io". And what I need is for him to convert to "Io! laossep".

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);
        }
    }
  • Possible duplicate of How to Invert a String?

  • 2

    @Marconi’s not a duplicate of that one. This other question is to invert the phrase as a whole, something that the OP was already doing, but the problem here is to invert only the words individually without reversing their order within the sentence. It’s a very similar and well-connected problem, but it’s different.

1 answer

3


First, that the variable palavra actually contains a phrase. So, to not leave things confused, let’s call it entrada.

You can use entrada.split(" ") to divide the input into the constituent words and then use your algorithm to invert them one by one. I also recommend using a StringBuilder to avoid creating a lot of Stringintermediate s that will be disposed of by the garbage collector and with this cause a relatively bad performance.

Your code goes 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.

  • 2

    Primeiro, que a variável palavra na verdade contém uma frase. Então, para não deixar as coisas confusas, vamos chamá-la de entrada loves those parts :)

  • 2

    To reverse a String, you could also use new StringBuilder(s).reverse().toString()

  • 1

    @hkotsubo In case it would be resultado.append(new StringBuilder(s).reverse().toString()); - however, I wanted to take advantage of the code that the author of the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.