String Algorithms
Scanning a String Character by Character
A for loop is the standard way to visit every character of a string — start at 0, stop before length():
String autoName = "BlueAlliance-Left";
int dashCount = 0;
for (int i = 0; i < autoName.length(); i++)
{
if (autoName.substring(i, i + 1).equals("-"))
{
dashCount++;
}
}
Use a for loop when you know you want to check every character. Use a while loop instead when you're searching for something and don't know in advance how many characters you'll need to check — see the find-and-replace pattern below.
Find and Replace with indexOf + substring
A while loop paired with indexOf repeatedly finds and processes one match at a time, until none remain:
String name = "Alli1ance";
int i = 0;
while (name.indexOf("1") >= 0)
{
i = name.indexOf("1");
String firstPart = name.substring(0, i);
String lastPart = name.substring(i + 1);
name = firstPart + "l" + lastPart; // replace the "1" with "l"
}
Each pass finds the next occurrence, because the string was already reassigned — the search always runs against the current (updated) value of name.
Building a New String
Since strings are immutable, "building" one really means starting with an empty string and concatenating onto it inside a loop:
String reversed = "";
for (int i = 0; i < autoName.length(); i++)
{
String letter = autoName.substring(i, i + 1);
reversed = letter + reversed; // prepend — builds the string backwards
}
Common Pitfalls
- Starting a string-scanning loop at 1 instead of 0. The first character is always at index 0 — starting at 1 skips it.
- Using
<=instead of<againstlength().i <= autoName.length()reads one index past the end and throwsIndexOutOfBoundsException. - An infinite loop in a find-and-replace pattern. If the replacement text itself still contains the thing you're searching for,
indexOffinds it again forever — make sure each pass genuinely reduces what's left to find.
Key Takeaways
forloops fit scanning every character;whileloops fit searching for an unknown number of matches.- A find-and-replace loop combines
indexOf(to locate) withsubstring(to rebuild around the match), reassigning the string each pass. - Building a new string from scratch means starting empty and concatenating inside a loop — strings can't be modified in place.
Derived from csawesome-2026: unit-2-selection-and-iteration/2.10-implementing-string-algorithms.md (CSA 2.10)