You could reverse a string by copying characters from one string starting at the end to another, starting at the beginning.
With paper and pencil, reversing a string is easy. Copy characters from the original string right to left to the new string left to right.
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" ) ); } }
The body of the for
loop executes once per character.
(Tricky Thought Question: )
How many objects does reverse()
construct in this
example?