Tuesday, October 26, 2010

String Example : String Reverser

The reverse() method in the following program follows that idea. The variable j indexes characters in the original string starting at the rightmost character, data.length()-1, and moves left until it reaches the first character. Each character is appended on the right of a new String.
public class ReverseTester
{

  public static String reverse( String data )
  {
    String rev = new String();

    for ( int j=data.length()-1; j >= 0; j-- )
      rev += data.charAt(j);

    return rev;
  }

  public static void main ( String[] args )
  {
    System.out.println( reverse( "Hello" ) );
  }
}

No comments:

Post a Comment

Chitika