1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
/* Java String Reverse example. This example shows how to reverse a given string */ public class StringReverseExample { public static void main(String args[]){ //declare orinial string String strOriginal = "Hello World"; System.out.println("Original String : " + strOriginal); /* The easiest way to reverse a given string is to use reverse() method of java StringBuffer class. reverse() method returns the StringBuffer object so we need to cast it back to String using toString() method of StringBuffer */ strOriginal = new StringBuffer(strOriginal).reverse().toString(); System.out.println("Reversed String : " + strOriginal); } } /* Output of the program would be : Original String : Hello World Reversed String : dlroW olleH */ |
[code]
/* Here is the full example of reversing a string in the form of a method. It’s as simple as this!!! */
import java.util.Scanner;
public class PrintBack{
public static void main(String[] args)
{
DoPrint();
}
static void DoPrint()
{
Scanner boom = new Scanner(System.in);
String name;
int i;
System.out.print(“Enter a sentence: “);
name = boom.nextLine();
i = name.length()-1;
while (i >= 0){
System.out.print(name.charAt(i));
i–;
}
}
}
[/code]
can you please edit it, that will print the sentence reversed without ruining the letters…
example: I am cool
reversed: cool am i
I managed to do this with a String array. I was wondering how to do it without using an array and then stumbled across this algorithm. Much simpler than I’d presumed. Thanks a lot.
I have the site bookmarked.
i = name.length()-1;
why it needs -1 in that code??
It requires -1 because all strings end with a ‘\0’ character… while doing the reverse the null is not needed.. so -1 is used else the string will end up reversed one short.