πŸ““4.3: Loops & Strings

Table of Contents


πŸ“– This page is a condensed version of CSAwesome Topic 4.3

πŸ“ Take notes in a Codespace during class, coding along with the instructor.

  1. Go to GitHub and click on your picture in the TOP RIGHT corner
  2. Select Your repositories
  3. Open CS2-Unit-4-Notes
  4. Now on your repository, click and select the Codespaces tab
  5. Click Create Codespace on main (unless you already have one listed there), wait for the environment to load, then you’re ready to code!

Loops & Strings

Loops are often used for String Traversals or String Processing where the code steps through a string character by character. In topic 2.6 and 2.7, we learned to use String objects and built-in string methods to process strings. In this lesson, we will write our own loops to process strings.

Remember that String objects are a sequence of characters where each character is stored at an index (position) starting from 0:

image

πŸ”„ Loops that process strings should initialize the loop control variable (counter) at 0… recall that the first character in a Java String is located at index 0 and the last character is at length() - 1.

The String methods (covered in lesson 2.7 and given in the AP CSA Reference Sheet) that are most often used to process strings are:

  • int length() : returns the number of characters in a String object.

  • int indexOf(String str) : returns the index of the first occurrence of str or -1 if str is not found.

  • String substring(int from, int to) : returns the substring beginning at index from and ending at index (to – 1).
    • Note that s.substring(i,i+1) returns the single character at index i.
  • String substring(int from) : returns substring(from, length()).

While Loops: Find and Replace

A while loop can be used with the String indexOf method to find certain characters in a string and process them, usually using the substring method:

String s = "example";
int i = 0;
// Loop while there is still an 'a' in s
while (s.indexOf("a") >= 0)
{
     // Find and save the next index for an a
     i = s.indexOf("a");
     // Process the string at that index
     String ithLetter = s.substring(i,i+1);
     ...
}

πŸ“š Google has been scanning old books and then using software to read the scanned text. But, the software can get things mixed up like using the number 1 for the letter l.

πŸ” The following code loops through a string finding and replacing all 1’s with l’s:

String message = "Have a 1ong and happy 1ife";
int index = 0;

while (message.indexOf("1") >= 0)
{
    // Find the next index for 1
    index = message.indexOf("1");
    System.out.println("Found a 1 at index: " + index);
    // Replace the 1 with a l at index by concatenating substring up to
    // index and then the rest of the string.
    String firstpart = message.substring(0, index);
    String lastpart = message.substring(index + 1);
    message = firstpart + "l" + lastpart;
    System.out.println("Replaced 1 with l at index " + index);
    System.out.println("The message is currently " + message + " but we aren't done looping yet!");
}
System.out.println("Cleaned text: " + message);
  1. Trace through the code below with a partner and explain how it works on the given message. You can run it line by line in the Java visualizer.

    Note that indexOf here can work repeatedly to find the next occurrence of a 1 because they are replaced as soon as they are found.

  2. Add code for a counter variable to count the number of 1’s replaced in the message and print it out.
  3. Change the message to have more mistakes with 1’s to test it.

For Loops: Reversing Strings

for loops can also be used to process strings, especially in situations where you know you will visit every character.

while loops are often used with strings when you are looking for a certain character or substring in a string and do not know how many times the loop needs to run. for loops are used when you know you want to visit every character.

for loops with strings usually start at 0 and use the string’s length() for the ending condition to step through the string, character by character.

String s = "example";
// loop through the string from 0 to length
for(int i=0; i < s.length(); i++)
{
      String ithLetter = s.substring(i,i+1);
      // Process the string at that index
      ...
}

Here is a for loop that creates a new string that reverses the string s. We start with a blank string sReversed and build up our reversed string in that variable by copying in characters from the string s. You can also run this code in this Java visualizer link.

String s = "Hello";
String sReversed = "";
String ithLetter;

for (int i = 0; i < s.length(); i++)
{
    ithLetter = s.substring(i, i + 1);
    // add the letter at index i to what's already reversed.
    sReversed = ithLetter + sReversed;
}

System.out.println(s + " reversed is " + sReversed);

πŸ’¬ DISCUSS:

  • What would happen if you started the loop at 1 instead?
  • What would happen if you used the <= operator instead of <?
  • What would happen if you changed the order in which you added the ithLetter?

⭐️ Summary

  • Loops can be used to traverse or process a String.
  • There are standard algorithms that utilize String traversals to:
    • Find if one or more substrings has a particular property
    • Determine the number of substrings that meet specific criteria
    • Create a new string with the characters reversed

πŸ›‘ When class ends, don’t forget to SAVE YOUR WORK!

  1. Navigate to the Source Control menu on the LEFT sidebar
  2. Type a brief commit message in the box, for example: updated Main.java
  3. Click the button on the LEFT menu
  4. Click the button on the LEFT menu
  5. Finally you can close your Codespace!

Acknowledgement

Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.