4.3. Loops and Strings — AP CSAwesome (2024)

Time estimate: 90 min.

Loops are often used for String Traversals or String Processing where the code steps through a string character by character. In lesson 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 strings are a sequence of characters where each character is at a position or index starting at 0.

Note

The first character in a Java String is at index 0 and the last characters is at length() - 1. So loops processing Strings should start at 0!

The String methods (covered in lesson 2.7 and given in the AP CSA Java Quick 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 character at index i.

  • String substring(int from) : returns substring(from, length()).

4.3.1. While Find and Replace Loop

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;// while there is an a in swhile (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.

Check Your Understanding

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.

Coding Exercise

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.

4.3.2. For Loops: Reverse String

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

Note

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 lengthfor(int i=0; i < s.length(); i++){ String ithLetter = s.substring(i,i+1); // Process the string at that index ...}

Check Your Understanding

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.

Coding Exercise

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?

4.3.3. Programming Challenge : String Replacement Cats and Dogs

Are you a cat person or a dog person? The code below prints a nice message about cats, but if you’re a dog person, you might not agree.

  1. 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.

  2. (Optional - not autograded) add a counter to count the number of replacements and print it out.

  3. (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.

Write a while loop that replaces every occurrence of “cat” in the message with “dog” using the indexOf and substring methods.

4.3.4. 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

For more practice with string processing, see the Free Response Question in the Practice and Summary section of this unit.

You have attempted of activities on this page

4.3. Loops and Strings — AP CSAwesome (2024)
Top Articles
10 Best Crypto Trading Strategies for Traders in 2023
Todays Silver Rate - 100 Gram & 1Kg Silver Price in India on 13th Sep 2024
Navicent Human Resources Phone Number
Ffxiv Act Plugin
AllHere, praised for creating LAUSD’s $6M AI chatbot, files for bankruptcy
Pet For Sale Craigslist
Craigslist Campers Greenville Sc
Chelsea player who left on a free is now worth more than Palmer & Caicedo
GAY (and stinky) DOGS [scat] by Entomb
Cinepacks.store
Music Archives | Hotel Grand Bach - Hotel GrandBach
270 West Michigan residents receive expert driver’s license restoration advice at last major Road to Restoration Clinic of the year
Sitcoms Online Message Board
Walgreens On Nacogdoches And O'connor
7440 Dean Martin Dr Suite 204 Directions
Craigslist Farm And Garden Tallahassee Florida
Colorado mayor, police respond to Trump's claims that Venezuelan gang is 'taking over'
Itziar Atienza Bikini
Craigslist Mt Pleasant Sc
Publix Super Market At Rainbow Square Shopping Center Dunnellon Photos
Eine Band wie ein Baum
Amazing deals for Abercrombie & Fitch Co. on Goodshop!
Happy Homebodies Breakup
Fleet Farm Brainerd Mn Hours
Divina Rapsing
Roanoke Skipthegames Com
Culver's.comsummerofsmiles
Speechwire Login
Spirited Showtimes Near Marcus Twin Creek Cinema
James Ingram | Biography, Songs, Hits, & Cause of Death
Abga Gestation Calculator
Ellafeet.official
Fedex Walgreens Pickup Times
6143 N Fresno St
Panchitos Harlingen Tx
THE 10 BEST Yoga Retreats in Konstanz for September 2024
Kgirls Seattle
Spn-523318
Craigslist Free Manhattan
Final Fantasy 7 Remake Nexus
Post A Bid Monticello Mn
Ehome America Coupon Code
[Teen Titans] Starfire In Heat - Chapter 1 - Umbrelloid - Teen Titans
Gary Vandenheuvel Net Worth
Lawrence E. Moon Funeral Home | Flint, Michigan
Mail2World Sign Up
Bradshaw And Range Obituaries
Goosetown Communications Guilford Ct
91 East Freeway Accident Today 2022
8663831604
Palmyra Authentic Mediterranean Cuisine مطعم أبو سمرة
Qvc Com Blogs
Latest Posts
Article information

Author: Aron Pacocha

Last Updated:

Views: 5439

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Aron Pacocha

Birthday: 1999-08-12

Address: 3808 Moen Corner, Gorczanyport, FL 67364-2074

Phone: +393457723392

Job: Retail Consultant

Hobby: Jewelry making, Cooking, Gaming, Reading, Juggling, Cabaret, Origami

Introduction: My name is Aron Pacocha, I am a happy, tasty, innocent, proud, talented, courageous, magnificent person who loves writing and wants to share my knowledge and understanding with you.