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
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
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);
}
}
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
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 .
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);
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.