Unit 2.10: Standard String Algorithms
By combining iteration with the String class methods, we can implement several standard and powerful algorithms for processing strings.
Common String Algorithms
String Traversal
- String algorithms combine loops with indexing (using
substringandindexOf) to examine characters one by one. This process is called "traversal."
Finding Substrings with a Particular Property
This involves iterating through a string and checking each character or substring for a desired characteristic.
Task: Counting vowels in a string using a loop and indexOf.
public class VowelCounter {
public static void main(String[] args) {
String text = "Hello, World!";
int vowelCount = 0;
String vowels = "aeiouAEIOU";
for (int i = 0; i < text.length(); i++) {
String letter = text.substring(i, i + 1);
// If the letter is found in the vowels string, it is a vowel
if (vowels.indexOf(letter) != -1) {
vowelCount++;
}
}
System.out.println("Number of vowels: " + vowelCount); // Output: 3
}
}
Counting Substrings that Meet Specific Criteria
This involves iterating through a string to find how many times a specific substring appears.
EXCLUSION STATEMENT
- The
indexOf(String str, int fromIndex)method used in the example below is outside the scope of the AP Computer Science A course and exam, which only requires theindexOf(String str)method. However, it is a common and efficient way to search for multiple occurrences.
Task: Counting occurrences of a specific pattern within a string.
public class SubstringCounter {
public static void main(String[] args) {
String text = "abababa";
String sub = "aba";
int count = 0;
int index = text.indexOf(sub);
// Keep searching as long as indexOf finds the substring
while (index != -1) {
count++;
// Start the next search from the character after the last match
index = text.indexOf(sub, index + 1);
}
System.out.println("'" + sub + "' appears " + count + " times."); // Output: 3
}
}
Creating a Reversed String
This involves iterating through the original string from back to front and building a new string character by character.
Task: Reversing a string using backward iteration.
public class StringReverser {
public static void main(String[] args) {
String original = "hello";
String reversed = "";
for (int i = original.length() - 1; i >= 0; i--) {
reversed = reversed + original.substring(i, i + 1);
}
System.out.println("Reversed string: " + reversed); // Output: "olleh"
}
}