# 2.10 Implementing String Algorithms

Each coding exercise has its own folder. Open its `.java` file and press **Run** to try it. **Run Tests** checks every graded exercise in this lesson at once.

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:

- 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

Remember that strings are a sequence of characters where each character is at a position or **index** starting at 0.

![A string with the position (index) shown above each character](images/stringIndicies.png)

*A string with the position (index) shown above each character*

> 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 a previous lesson and given in the [AP CSA Java Quick Reference Sheet](https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-java-quick-reference.pdf)) 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()).

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

```java
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](http://www.pythontutor.com/visualize.html#code=public%20class%20RemoveAs%20%7B%0A%20%20%20%0A%20%20%20public%20static%20void%20main%28String%5B%5D%20args%29%0A%20%20%20%7B%0A%0A%20%20%20%20%20%20String%20s%20%3D%20%22are%20apples%20tasty%20without%20a's%3F%22%3B%20%0A%20%20%20%20%20%20int%20index%20%3D%200%3B%0A%20%20%20%20%20%20System.out.println%28%22Original%20string%3A%20%22%20%2B%20s%29%3B%0A%0A%20%20%20%20%20%20//%20while%20there%20is%20an%20a%20in%20s%0A%20%20%20%20%20%20while%20%28s.indexOf%28%22a%22%29%20%3E%3D%200%29%0A%20%20%20%20%20%20%7B%0A%20%20%20%0A%20%20%20%20%20%20%20%20%20//%20Find%20the%20next%20index%20for%20an%20a%0A%20%20%20%20%20%20%20%20%20index%20%3D%20s.indexOf%28%22a%22%29%3B%0A%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20//%20Remove%20the%20a%20at%20index%20by%20concatenating%20%0A%20%20%20%20%20%20%20%20%20//%20substring%20up%20to%20index%20and%20then%20rest%20of%20the%20string.%0A%20%20%20%20%20%20%20%20%20s%20%3D%20s.substring%280,index%29%20%2B%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20s.substring%28index%2B1%29%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%7D%20//%20end%20loop%20%0A%20%20%0A%20%20%20%20%20%20System.out.println%28%22String%20with%20a's%20removed%3A%22%20%2B%20s%29%3B%0A%20%20%20%0A%20%20%20%7D%20//%20end%20method%0A%7D&cumulative=false&curInstr=23&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=java&rawInputLstJSON=%5B%5D&textReferences=false).

> Check your understanding: The following program removes all the a’s from a string, but the code is mixed up. — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-10-strings-loops.html#removeA

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](http://www.pythontutor.com/visualize.html#code=public%20class%20Test%0A%20%20%20%7B%0A%20%20%20%20%20%20public%20static%20void%20main%28String%5B%5D%20args%29%0A%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20String%20message%20%3D%20%22Have%20a%201ong%20and%20happy%201ife%22%3B%20%0A%20%20%20%20%20%20%20%20int%20index%20%3D%200%3B%0A%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20//%20while%20more%201s%20in%20the%20message%0A%20%20%20%20%20%20%20%20while%20%28message.indexOf%28%221%22%29%20%3E%3D%200%29%0A%20%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20//%20Find%20the%20next%20index%20for%201%0A%20%20%20%20%20%20%20%20%20%20%20index%20%3D%20message.indexOf%28%221%22%29%3B%0A%20%20%20%20%20%20%20%20%20%20%20System.out.println%28%22Found%20a%201%20at%20index%3A%20%22%20%2B%20index%29%3B%0A%20%20%20%20%20%20%20%20%20%20%20//%20Replace%20the%201%20with%20a%20l%20at%20index%20by%20concatenating%20substring%20up%20to%20index%20and%20then%20the%20rest%20of%20the%20string.%0A%20%20%20%20%20%20%20%20%20%20%20String%20firstpart%20%3D%20message.substring%280,index%29%3B%0A%20%20%20%20%20%20%20%20%20%20%20String%20lastpart%20%3D%20message.substring%28index%2B1%29%3B%0A%20%20%20%20%20%20%20%20%20%20%20message%20%3D%20firstpart%20%2B%20%22l%22%20%2B%20lastpart%3B%0A%20%20%20%20%20%20%20%20%20%20%20System.out.println%28%22Replaced%201%20with%20l%20at%20index%20%22%20%2B%20index%29%3B%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20System.out.println%28%22Cleaned%20text%3A%20%22%20%2B%20message%29%3B%0A%20%20%20%20%20%20%7D%0A%20%20%20%7D&cumulative=false&curInstr=21&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=java&rawInputLstJSON=%5B%5D&textReferences=false&curInstr=0)) 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](http://www.pythontutor.com/visualize.html#code=public%20class%20Test%0A%20%20%20%7B%0A%20%20%20%20%20%20public%20static%20void%20main%28String%5B%5D%20args%29%0A%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20String%20message%20%3D%20%22Have%20a%201ong%20and%20happy%201ife%22%3B%20%0A%20%20%20%20%20%20%20%20int%20index%20%3D%200%3B%0A%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20//%20while%20more%201s%20in%20the%20message%0A%20%20%20%20%20%20%20%20while%20%28message.indexOf%28%221%22%29%20%3E%3D%200%29%0A%20%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20//%20Find%20the%20next%20index%20for%201%0A%20%20%20%20%20%20%20%20%20%20%20index%20%3D%20message.indexOf%28%221%22%29%3B%0A%20%20%20%20%20%20%20%20%20%20%20System.out.println%28%22Found%20a%201%20at%20index%3A%20%22%20%2B%20index%29%3B%0A%20%20%20%20%20%20%20%20%20%20%20//%20Replace%20the%201%20with%20a%20l%20at%20index%20by%20concatenating%20substring%20up%20to%20index%20and%20then%20the%20rest%20of%20the%20string.%0A%20%20%20%20%20%20%20%20%20%20%20String%20firstpart%20%3D%20message.substring%280,index%29%3B%0A%20%20%20%20%20%20%20%20%20%20%20String%20lastpart%20%3D%20message.substring%28index%2B1%29%3B%0A%20%20%20%20%20%20%20%20%20%20%20message%20%3D%20firstpart%20%2B%20%22l%22%20%2B%20lastpart%3B%0A%20%20%20%20%20%20%20%20%20%20%20System.out.println%28%22Replaced%201%20with%20l%20at%20index%20%22%20%2B%20index%29%3B%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20System.out.println%28%22Cleaned%20text%3A%20%22%20%2B%20message%29%3B%0A%20%20%20%20%20%20%7D%0A%20%20%20%7D&cumulative=false&curInstr=21&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=java&rawInputLstJSON=%5B%5D&textReferences=false&curInstr=0). 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.

### Exercise 1

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.

> Open the `01-string-replace1` folder and edit `FindAndReplace.java`. Press **Run** to try it; **Run Tests** checks it (1 test).

## For Loops: Reverse String

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

```java
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
   ...
}
```

> 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. — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-2-10-strings-loops.html#countEs

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](http://www.pythontutor.com/visualize.html#code=%20%20%20public%20class%20ReverseString%0A%20%20%20%7B%0A%20%20%20%20%20%20public%20static%20void%20main%28String%5B%5D%20args%29%0A%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20String%20s%20%3D%20%22Hello%22%3B%0A%20%20%20%20%20%20%20%20String%20sReversed%20%3D%20%22%22%3B%0A%20%20%20%20%20%20%20%20String%20ithLetter%3B%0A%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20for%28int%20i%3D0%3B%20i%20%3C%20s.length%28%29%3B%20i%2B%2B%29%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20ithLetter%20%3D%20s.substring%28i,i%2B1%29%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20//%20add%20the%20letter%20at%20index%20i%20to%20what%20is%20already%20reversed.%0A%20%20%20%20%20%20%20%20%20%20%20%20sReversed%20%3D%20ithLetter%20%2B%20sReversed%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20System.out.println%28s%20%2B%20%22%20reversed%20is%20%22%20%2B%20sReversed%29%3B%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%7D&cumulative=false&curInstr=25&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=java&rawInputLstJSON=%5B%5D&textReferences=false&curInstr=0).

### Exercise 2

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 13?

> Open the `02-reverseString` folder and edit `ReverseString.java`. Press **Run** to try it; **Run Tests** checks it (1 test). Its test checks your code, not what it prints: “Code has been changed”.

## Coding Challenge: String Replacement Cats and Dogs

![Cat or Dog](images/catordog.jpg)

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.

### Exercise 3

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

> Open the `03-challenge-string-replace` folder and edit `ChallengeReplace.java`. Press **Run** to try it; **Run Tests** checks it (4 tests).

## Summary

- Loops can be used to traverse or process a string.
- (AP 2.10.A.1) There are standard string algorithms 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 [FRQ 1 MessageBuilder](/lessons/CSA-2-FRQ-1-MessageBuilder-with-Loops-and-Strings).
