2. String Iteration

2.1. Objectives

  • Utilize a for loop to iterate through a String

2.2. Time Goal

  • 15 minutes on this section

2.3. Key Terms

iteration
Executing a sequence of statements repeatedly.

2.4. Exercises

Note

The following loop iterates the characters in fruit and displays them, one on each line:

for (int i = 0; i < fruit.length(); i++) {
   char letter = fruit.charAt(i);
   System.out.println(letter);
}

Strings provide a method called length that returns the number of characters in the string. Because it is a method, you have to invoke it with the empty argument list, (). When i is equal to the length of the string, the condition becomes false and the loop terminates.

To find the last letter of a string, you might be tempted to do something like:

int length = fruit.length();
char last = fruit.charAt(length);      // wrong!

This code compiles and runs, but invoking the charAt method throws a StringIndexOutOfBoundsException. The problem is that there is no sixth letter in “banana”. Since we started counting at 0, the 6 letters are indexed from 0 to 5. To get the last character, you have to subtract 1 from length.

int length = fruit.length();
char last = fruit.charAt(length - 1);  // correct

Many string algorithms involve reading one string and building another. For example, to reverse a string, we can add one character at a time:

String s = "apples";
String r = "";
for (int i = s.length() - 1; i >= 0; i--) {
   r += s.charAt(i);
}

The initial value of r is “”, which is the empty string. The loop iterates the letters of s in reverse order. Each time through the loop, it creates a new string and assigns it to r. When the loop exits, r contains the letters from s in reverse order. So the result of reverse(“banana”) is “ananab”.

Write a class that does the following:

  • Declares a String variable and assigns “banana” to it.
  • Using a for loop prints of every other letter starting with the first letter, the output should be bnn
  • Do not look at the answer before trying to solve on your own, look at hints first.
https://trinket.io/java/a14ba9961b
Next Section - Methods Lab