Loops are often used for String Traversals or String Processing algorithms where the code steps through a string character by character. In previous lessons, 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. There are standard string algorithms to:
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 character at index i.
String s = "example";
int i = 0;
// while there is 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);
...
}
The example in the mixed up code below finds and removes all the letter aβs in a string. You can watch it in action in this Java visualizer.
The following program removes all the aβs from a string, but the code is mixed up. Drag the blocks from the left area into the correct order in the right area. Click on the βCheck Meβ button to check your solution.
public static void main(String[] args)
{
---
String s = "are apples tasty without an a?";
int index = 0;
System.out.println("Original string: " + s);
---
// while there is an a in s
while (s.indexOf("a") >= 0)
{
---
// Find the next index for an a
index = s.indexOf("a");
---
// Remove the a at index by concatenating
// substring up to index and then rest of the string.
s = s.substring(0,index) +
s.substring(index+1);
---
} // end loop
---
System.out.println("String with a's removed:" + s);
---
} // end method
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. Try the code below (and in the Java visualizer) to clean up scanning mistakes like this.
The following code loops through a string replacing all 1βs with lβs. 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.
Change the code to 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.
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.
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
...
}
Activity2.10.3.
The following main method has the correct code to count the number of eβs in a string, but the code is mixed up. Drag the blocks from the left area into the correct order in the right area. Click on the βCheck Meβ button to check your solution.
public static void main(String[] args)
{
---
String message = "e is the most frequent English letter.";
int count = 0;
---
for(int i=0; i < message.length(); i++)
{
---
if (message.substring(i,i+1).equalsIgnoreCase("e"))
---
count++;
---
}
---
System.out.println(count);
---
}
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 or by clicking on the Code Lens button below.
What would happen if you started the loop at 1 instead? What would happen if you used <= instead of <? What would happen if you changed the order in which you added the ithLetter in line 12?
Write some code below that changes every occurrence of βcatβ to βdogβ in the message. This code will be more like the first program in this lesson where we replaced 1βs with lβs.
(Optional - challenging and not autograded) What if you like both cats and dogs? After you replace βcatβ with βdogβ, add another loop that looks for the word βdogsβ and adds β and catsβ to it. Do not replace βdogβ, just replace βdogsβ. This will just replace the first sentence in the example below but you can add other sentences to test. For this loop, you will need to use a special version of indexOf that searches from a given index, so that you donβt end up with an infinite loop that keeps finding the first βdogsβ. Make sure you add a variable fromIndex that is initialized to 0 and that is changed each time through the loop to skip over the last word that was found.
int indexOf(String target, int fromIndex) searches left-to-right for the target substring, but starts the search at the given fromIndex. You are not required to know this version of indexOf for the AP CSA exam, but you can use it (and any valid Java code) in the Free Response Questions.