Hints for Lab 2
- You can create an empty string as follows
String r = "";
or String r = new String();
.
- Class
String
provides two method that you might find useful:
length()
: returns the number of characters in a string.
charAt(index)
: returns the character of a string in the position indicated by the value of the parameter index
. The first character of a string is in index 0, the second character is in index 1, and so on. The last character of a string is in index length()-1
.
For example if s = "hello";
then s.length()
is 5, s.charAt(0)
is 'h', s.charAt(1)
is 'e', and s.charaAt(s.length()-1
is 'o'.
- To reverse a string
s
we might first create an empty string r
then read one by one the characters of s
from right to left. The rightmost character of s
is added to r
, then the second rightmost character of s
is appended to r
and so on.
- To read the characters of
s
from right to left, we can use a for
loop:
    for (int i = s.length()-1; i > = 0; --i)
          ...s.charAt(i)...
- To append a character
c
to a string r
we can use the concatenation operator "+":
     r = r + c;
- Once the reversed string
r
has been computed, to return it use the statement return r;