Traversing a String
A string traversal visits the positions of a string in turn, starting at position 0. Here the string is a short strand of DNA, written with the letters A, C, G, and T.
String strand = "CGATTGCA";
for (int i = 0; i < strand.length(); i++)
{
String base = strand.substring(i, i + 1);
System.out.print(base + " ");
}
This prints
C G A T T G C A. The loop starts at 0 and continues as long as i is below the length, 8, so it visits positions 0 through 7. Each base is a one-character String.Counting
A count of the G and C letters in the strand starts at 0 before the loop and goes up at each position that passes.
int gc = 0;
for (int i = 0; i < strand.length(); i++)
{
String base = strand.substring(i, i + 1);
if (base.equals("G") || base.equals("C"))
{
gc++;
}
}
The letters at positions 0, 1, 5, and 6 pass, so
gc ends at 4. The test uses equals, because == compiles but compares references, and a substring is a new object, so the test would fail even where the letters match.Building a reversed copy
A new string can be built one piece at a time, starting from the empty string
"".String reversed = "";
for (int i = 0; i < strand.length(); i++)
{
reversed = strand.substring(i, i + 1) + reversed;
}
Each letter goes in front of everything collected so far. After three passes
reversed holds AGC, and after all eight it holds ACGTTAGC. Writing reversed + strand.substring(i, i + 1) instead would add each letter at the end and build a copy in the original order.Looking at several characters
Some questions need a run of characters. A run of 4 that starts at position
i is strand.substring(i, i + 4), and it only fits where i + 4 is at most the length. So the loop stops at strand.length() - 4, which is 4.boolean hasTTGC = false;
for (int i = 0; i <= strand.length() - 4; i++)
{
if (strand.substring(i, i + 4).equals("TTGC"))
{
hasTTGC = true;
}
}
The loop checks five runs, at positions 0 through 4, and the run at position 3 is
TTGC, so hasTTGC ends true. With the full-length condition i < strand.length(), position 5 would ask for substring(5, 9), beyond the last position, and the program would stop with a StringIndexOutOfBoundsException.