Java; a program that reads a phrase and displays the words in the reverse order

2

Hi, I do not know how to make this program read a phrase and show it in reverse, for example:

String frase = "Me gusta programar.";

and that shows:

System.out.println("programar. gusta Me");

Thank you community: D

    
asked by AlejandroB 17.01.2018 в 19:37
source

4 answers

4

you can pass it to an array, then traverse it from the end to the beginning so that it collects the last chains and is concatenated:

import java.util.*;
import java.lang.*;

class Rextester
{  
    public static void main(String args[])
    {
        String cadena="hola como estas";
        String [] array=cadena.split(" ");
        String invertido="";
        for(int i=array.length-1;i>=0; i--){
           invertido=invertido+" "+array[i];
        }
        System.out.println(invertido);
    }
}
    
answered by 17.01.2018 / 19:56
source
2

With JAVA 8:

import java.util.ArrayDeque;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Main {
  public static void main(String[] args) {
        Stream.of("hola que mas".split(" "))
            .collect(Collectors.toCollection(ArrayDeque::new))
            .descendingIterator()
            .forEachRemaining(System.out::println);
    }
}
  

hello what else > more than hello

Demo

    
answered by 17.01.2018 в 20:51
2

You can create an array from the original string to get the words:

 String frase = "Me gusta programar.";
 String[] strWords =  frase.split(" ");

later invert the values of the array

   List<String> list = Arrays.asList(strWords);
   Collections.reverse(list);

in this way build the required string.

Example:

    String  resultado ="";
    String frase = "Me gusta programar.";
    String[] strWords =  frase.split(" ");
    List<String> list = Arrays.asList(strWords);
    Collections.reverse(list);

    for (String part : list) {
        resultado += part + " ";
    }
    System.out.println(resultado);

to get as output:

programar. gusta Me 

I add an online example .

    
answered by 17.01.2018 в 21:16
0

There are two ways to do that in java, the first one is like this:

String sCadena = "LineaDeCodigo";

for (int x=sCadena.length()-1;x>=0;x--)
		sCadenaInvertida = sCadenaInvertida + sCadena.charAt(x);
    System.out.println(sCadenaInvertida);
that was the way they answered you before. but there is another way cleaner and easier in this way:

and the other way in which you can use a java method and make it easier is as follows:

We define the String and load it into the StringBuffer:

String cadena= "abuelita, abuelita";
StringBuilder builder=new StringBuilder(cadena);

We execute the .reverse () of the StringBuffer and convert the StringBuffer into a string using the .toString () method

String sCadenaInvertida=builder.reverse().toString();

Something very simple and clean in your code.

    
answered by 17.01.2018 в 20:37