How to Display String in Reverse Order in Java


This is the simple java programming exercise on string. The program will ask to enter a string and then display the string in reverse order e.g. given String is "my hands are dirty" its reverse order will be "dirty are hands my".

Source Code 

package newpackage.more;
/**
 *
 * @author Shan
 */
public class reverseString {
/**
     * @param args the command line arguments
     */
public static void main(String[] args) {
System.out.println("Original : Ali is a good boy");
System.out.println("Reverse :"+reverseString(" Ali is a good boy"));
}
public static String reverseString(String string)
{
String reverse="";
String substring[]=string.split(" ");

for(int i=(substring.length-1);i>=0;i--)
{
reverse = reverse + " "+ substring[i];
}

return reverse;
}
}

Output of the Program

How to Display String in Reverse Order in Java


Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.

1 comments:

  1. I prefer walk the array till the middle swapping 1st, 2nd, 3th .... with N-1-i

    for( int i = 0; i < array.length / 2; i++ ) {
    // TODO: swap in efficiently loop.
    }

    ReplyDelete