Standard String Algorithms
Loops that work through a string one character or one substring at a time: finding substrings with a property, counting substrings that meet a criterion, building reversed and filtered strings, and getting the loop bounds exactly right.
Strings are sequences of characters with indices from 0 to length() - 1, so a loop can visit them one position at a time. There are standard string algorithms to find if one or more substrings have a particular property, to determine the number of substrings that meet specific criteria, and to create a new string with the characters reversed. Each combines a loop over indices, the substring method to extract pieces, and selection or concatenation to test or build. Because strings are immutable, every "change" builds a new string.
1Visiting Each Character
The foundation of every string algorithm is a loop over the indices: for (int i = 0; i < word.length(); i++). Inside it, word.substring(i, i + 1) produces the single character at index i as a String, which can be compared with equals, searched with indexOf, or joined to another string.
The bound i < word.length() is exactly right for single characters: the last index is length() - 1, and substring(length() - 1, length()) is the last character. For the empty string the loop runs zero times, which is usually correct, since there are no characters to examine.
Storing the extracted character in a well-named variable, such as String letter = word.substring(i, i + 1);, makes the rest of the loop body easier to read and avoids repeating the substring call in every test. The variable is declared inside the loop because it is needed only for the current pass.
| Goal | Loop bounds | Key operation |
|---|---|---|
| Examine each character | for (int i = 0; i < s.length(); i++) | s.substring(i, i + 1) |
| Examine substrings of length k | for (int i = 0; i <= s.length() - k; i++) | s.substring(i, i + k) |
| Compare neighbors | for (int i = 0; i < s.length() - 1; i++) | s.substring(i, i + 1) vs s.substring(i + 1, i + 2) |
| Visit from the end | for (int i = s.length() - 1; i >= 0; i--) | Append each character |
How Many Times Does a Letter Appear?
Count the letter "s" in "mississippi".
String word = "mississippi";
int count = 0;
for (int i = 0; i < word.length(); i++)
{
if (word.substring(i, i + 1).equals("s"))
{
count++;
}
}
System.out.println(count);
4
- 1Visit every index from 0 to
length() - 1. - 2Extract one character as a string with
substring(i, i + 1), and compare it withequals. - 3Count matches: indices 2, 3, 5, 6.
substring(i, i + 1) is the basic pattern for examining each character.2Counting Characters With a Property
Counting combines the character loop with the frequency pattern: a counter starts at 0, and an if inside the loop increases it when the current character satisfies a test. The test can compare with a specific character, check a range, or test membership in a set of characters.
A convenient membership test uses indexOf: a string such as "aeiou" serves as the set, and "aeiou".indexOf(letter) returns −1 exactly when letter is not in it. This replaces a long condition like letter.equals("a") || letter.equals("e") || ... with one clear expression.
indexOf returns −1 exactly when a character is not in it.Counting Vowels
Count the vowels in "education".
String word = "education";
String vowels = "aeiou";
int count = 0;
for (int i = 0; i < word.length(); i++)
{
String letter = word.substring(i, i + 1);
if (vowels.indexOf(letter) >= 0)
{
count++;
}
}
System.out.println(count);
5
- 1The property test.
vowels.indexOf(letter)is −1 for consonants and 0 to 4 for vowels (Figure 1). - 2The vowels in "education": e, u, a, i, o.
indexOf against a string of allowed characters avoids a long chain of || comparisons.word.substring(i, i + 1) == "s" compares references, and a substring is a new object, so the result is false even when the character is "s". Use equals.
3Substrings of Any Length
To count or find a longer pattern, slide a window of the pattern's length across the string. With k = pattern.length(), each pass examines word.substring(i, i + k) and compares it with the pattern. Every possible starting position is checked, so overlapping occurrences are all counted: "aa" appears three times in "aaaa."
The starting index must stop at word.length() - k, because a window starting later would need characters past the end. The loop condition is therefore i <= word.length() - k, or equivalently i < word.length() - k + 1. If the pattern is longer than the word, the condition is false at the start and the loop correctly finds nothing.
length() - k, taking substring(i, i + k) each time.Occurrences of a Two-Letter Pattern
Count how many times "an" appears in "banana" and "ss" appears in "mississippi".
public static int countPattern(String word, String pattern)
{
int k = pattern.length();
int count = 0;
for (int i = 0; i <= word.length() - k; i++)
{
if (word.substring(i, i + k).equals(pattern))
{
count++;
}
}
return count;
}
2
2
3
- 1Window length
k. Each pass examinessubstring(i, i + k). - 2Bounds. The last valid start is
word.length() - k, so the condition isi <= word.length() - k(Figure 4). - 3Overlaps count. In "aaaa", windows at 0, 1, and 2 all equal "aa": 3.
With i < word.length() and substring(i, i + 2), the final pass asks for an ending index one past the end and throws a StringIndexOutOfBoundsException. Reduce the bound by the window length minus 1.
4Finding Whether a Substring Has a Property
Sometimes the question is not "how many" but "is there any," and often "where." The loop examines substrings in order and stops as soon as one qualifies, reporting its starting index, or −1 if none does. Stopping early is done through the loop condition: a variable such as found starts at −1, the condition includes found == -1, and the body records the index when it finds a match.
Properties can involve more than one character. Comparing each character with its neighbor finds double letters; comparing a substring with a pattern finds a word; testing whether every character passes a check can be done by searching for the first character that fails and reporting whether none was found. Returning a Boolean or an index lets the caller decide what to do with the answer.
Is There a Double Letter?
Find whether a word contains two identical letters in a row, and where the first pair starts.
public static int firstDouble(String word)
{
int found = -1;
int i = 0;
while (found == -1 && i < word.length() - 1)
{
if (word.substring(i, i + 1).equals(word.substring(i + 1, i + 2)))
{
found = i;
}
i++;
}
return found;
}
1
-1
- 1Compare neighbors. Each pass compares the character at
iwith the one ati + 1, soistops atlength() - 2. - 2Stop at the first match. The loop condition includes
found == -1, so the search ends as soon as a pair is found. - 3"bookkeeper": "oo" starts at 1. "planet": no pair, so −1.
indexOf.| Standard algorithm | Result type | Example |
|---|---|---|
| Find if one or more substrings have a property | boolean or an index (−1 if none) | First double letter in "bookkeeper": 1 |
| Count substrings meeting a criterion | int | "an" in "banana": 2 |
| Create a new string with the characters reversed | String | "stressed" → "desserts" |
5Building New Strings
Because strings are immutable, algorithms that "change" a string actually build a new one, usually starting from the empty string "" and concatenating pieces in a loop. Adding each character to the end of the result copies the string; adding each character to the front reverses it. Looping from the last index down to 0 while appending also reverses.
Adding selection inside the loop filters the characters: append only those that pass a test, such as consonants or digits, and the result contains just those characters in their original order. Reversal combined with equals answers questions about the whole string, such as whether a word is a palindrome.
| i | word.substring(i, i + 1) | reversed after the pass |
|---|---|---|
| 0 | "s" | "s" |
| 1 | "t" | "ts" |
| 2 | "r" | "rts" |
| 3 | "e" | "erts" |
| … | … | … |
| 7 | "d" | "desserts" |
Creating a Reversed String
Reverse "stressed".
String word = "stressed";
String reversed = "";
for (int i = 0; i < word.length(); i++)
{
reversed = word.substring(i, i + 1) + reversed;
}
System.out.println(reversed);
desserts
- 1Add to the front. Each character goes before everything collected so far, so the first character ends up last.
- 2A new string.
wordis unchanged;reversedrefers to a new string each pass.
Palindromes
A palindrome reads the same in both directions. Test three words.
public static boolean isPalindrome(String word)
{
String reversed = "";
for (int i = word.length() - 1; i >= 0; i--)
{
reversed = reversed + word.substring(i, i + 1);
}
return reversed.equals(word);
}
true
true
false
- 1Reverse by counting down. The loop visits indices from
length() - 1to 0 and appends each character. - 2Compare with
equals. A word is a palindrome when its reversal has the same characters.
equals tests a property of the whole string.Removing the Vowels
Create a new string containing only the consonants of "programming".
String word = "programming";
String result = "";
for (int i = 0; i < word.length(); i++)
{
String letter = word.substring(i, i + 1);
if ("aeiou".indexOf(letter) == -1)
{
result = result + letter;
}
}
System.out.println(result);
prgrmmng
- 1Selection inside the loop decides which characters to keep.
- 2Appending keeps the kept characters in their original order.
Reversing or filtering produces a new string in another variable; the original is untouched. If the result is never stored, or the original variable is printed instead, the work is lost. Print or return the variable that holds the newly built string.
6Getting the Bounds Right
Most errors in string algorithms are off by one errors in the loop bounds, and they show up as a StringIndexOutOfBoundsException at run time. The rule is simple: for a window of length k, valid starting indices run from 0 to length() - k. Single characters use k = 1, neighbor comparisons use k = 2, and patterns use their own length.
Before running a string loop, check the last pass by hand: what is i, and what ending index does substring receive? If that ending index is greater than length(), the bound is one too large. Testing with very short strings, including strings shorter than the pattern and the empty string, catches the remaining edge cases.
k, the starting index can go up to length() - k. Going further throws a StringIndexOutOfBoundsException.A Window That Runs Past the End
Why does this loop fail, and how is it fixed?
String word = "level";
for (int i = 0; i < word.length(); i++)
{
System.out.println(word.substring(i, i + 2));
}
- 1The windows "le", "ev", "ve", "el" print for i = 0 to 3.
- 2At i = 4,
substring(4, 6)asks for an ending index of 6 in a string of length 5, which throws aStringIndexOutOfBoundsException. - 3Fix. For windows of length 2, use
i < word.length() - 1.
length() - k.The opposite error, i < word.length() - k without the equals sign, skips the last window. It does not crash, so it is easy to miss: counting "na" in "banana" with this bound finds 1 instead of 2. Check the final window explicitly.
Four Habits for String Algorithms
1. substring(i, i + 1)
Extract one character as a String; compare with equals.
2. Last Start = length() − k
Bound every window by its length.
3. Build From ""
Append to copy or filter; prepend to reverse.
4. −1 for Not Found
Report a position, or −1 when nothing qualifies.
There are standard string algorithms to find if one or more substrings have a particular property, to determine the number of substrings that meet specific criteria, and to create a new string with the characters reversed. Each loops over valid starting indices, uses substring to extract a character or a longer substring, and either tests it with equals or indexOf or joins it into a new string. For substrings of length k, the starting index runs from 0 to length() - k; going further results in a StringIndexOutOfBoundsException.