Java Reference
In-Depth Information
In Java we often think of a string as chunk of text, but you can also think of it as a
sequence of individual characters. Viewed in this light, a string is a lot like an array.
Recall that the individual elements of a string are of type
char
and that you can
access the individual character values by calling the
charAt
method.
The same techniques we have used to write array traversal algorithms can be used
to write string traversal algorithms. The syntax is slightly different, but the logic is
the same. Our array traversal template looks like this:
for (int i = 0; i < <array>.length; i++) {
<do something with array[i]>;
}
The corresponding string algorithm template looks like this:
for (int i = 0; i < <string>.length(); i++) {
<do something with string.charAt(i)>;
}
Notice that with arrays you refer to
length
without using parentheses, but with a
string you do use parentheses. Notice also that the array square bracket notation is
replaced with a call on the
charAt
method.
For example, you can count the number of occurrences of the letter “i” in
“Mississippi” with this code:
String s = "Mississippi";
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'i') {
count++;
}
}
This code would correctly compute that there are four occurrences of “i” in the
string. For another example, consider the task of computing the reverse of a string.
You can traverse the string building up a new version that has the letters in reverse
order by putting each new character at the front of string you are building up. Here is
a complete method that uses this approach:
public static String reverse(String text) {
String result = "";
for (int i = 0; i < text.length(); i++) {
result = text.charAt(i) + result;
}
Search WWH ::
Custom Search