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;
}
}
I prefer walk the array till the middle swapping 1st, 2nd, 3th .... with N-1-i
ReplyDeletefor( int i = 0; i < array.length / 2; i++ ) {
// TODO: swap in efficiently loop.
}