π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.
- Go to GitHub and click on your picture in the TOP RIGHT corner
- Select
Your repositories
- Open
CS2-Unit-4-Notes
- Now on your repository, click and select the
Codespaces
tab - 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
:
π 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 ofstr
or -1 ifstr
is not found. String substring(int from, int to)
: returns the substring beginning at indexfrom
and ending at index(to β 1)
.- Note that
s.substring(i,i+1)
returns the single character at indexi
.
- Note that
String substring(int from)
: returnssubstring(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);
- 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. - Add code for a
counter
variable to count the number of 1βs replaced in the message and print it out. - 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!
- Navigate to the
Source Control
menu on the LEFT sidebar - Type a brief commit message in the box, for example:
updated Main.java
- Click the button on the LEFT menu
- Click the button on the LEFT menu
- Finally you can close your Codespace!
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.