Loops over text
After this: Count, check and reverse the characters of a string with a loop.
On this page · 6 sections · 3 checks
How many vowels are in a word? Does a password contain at least one digit? Does level read the same backwards? Each of these questions needs a look at every character in turn, and that is what a loop is for.
In Lists you went through a list with a loop, one value at a time. A string is a row of characters, so a loop goes through it the same way: one character at a time, from position 0 to the end.
One character at a time
for ch in word:for (char ch : word.toCharArray()) { runs its lines once for each character of word, with the box ch holding the current character. For "hello" the lines run five times, with ch holding h, then e, then l, then l, then o.
Counting
The counting pattern from Lists works on text unchanged: start a count at 0, go through the characters, and add one for each character that passes a test. Here the test is "is this character a vowel?", which asks whether ch is one of the characters in "aeiou".
Work through "programming" by hand: p, r, no; o, yes, that is 1; g, r, no; a, yes, 2; m, m, no; i, yes, 3; n, g, no. Three vowels.
- Run the programRun it and watch the box ch take each character in turn. The box count goes up only when ch is a vowel.
word = "programming"count = 0for ch in word: if ch in "aeiou": count = count + 1print(count)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Python runs in the browser below. Java does not run here: step through the trace above instead, or paste the code into a Java tool on your computer.
Change the word to your own name, or change the test to count a single letter, ch == "m", and run again.
Checking a rule
A yes/no answer uses the same loop with a box that starts at no and turns to yes when a character passes the test. Here the test is "is this character a digit?".
pw = "ab12"has_digit = Falsefor ch in pw: if ch.isdigit(): has_digit = Trueprint(has_digit)True
String pw = "ab12";boolean hasDigit = false;for (char ch : pw.toCharArray()) { if (Character.isDigit(ch)) { hasDigit = true; }}System.out.println(hasDigit);true
The box starts at Falsefalse. The characters a and b fail the test, 1 passes it and turns the box to Truetrue, and 2 turns it to Truetrue again. A password with no digit would leave the box at Falsefalse.
Building backwards
A loop can build a new string as it goes, which the last lesson said is the way to get a changed string. To reverse a word, start with an empty string and put each character on the front of it.
- Start with
backwardsempty. hgoes on the front of nothing:h.egoes on the front:eh.lgoes on the front:leh. Then the secondl:lleh.ogoes on the front:olleh.
The line that does it is backwards = ch + backwards, with ch first. Watch the box grow.
word = "hello"backwards = ""for ch in word: backwards = ch + backwardsprint(backwards)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Both languages also have a one-line way to reverse a string. A word that reads the same backwards is called a palindrome, and checking for one is a comparison between the word and its reverse.
word = "level"print(word[::-1])print(word == word[::-1])level True
String word = "level";String backwards = new StringBuilder(word).reverse().toString();System.out.println(backwards);System.out.println(word.equals(backwards));level true
Check yourself
What does this print?
word = "banana"count = 0for ch in word: if ch in "aeiou": count = count + 1print(count)String word = "banana";int count = 0;for (char ch : word.toCharArray()) { if ("aeiou".indexOf(ch) >= 0) { count = count + 1; }}System.out.println(count);The line that updates the count is missing. Complete it so that the program prints 3 for programming.
word = "programming"count = 0for ch in word: if ch in "aeiou": ____________________ # ← add one to the countprint(count)String word = "programming";int count = 0;for (char ch : word.toCharArray()) { if ("aeiou".indexOf(ch) >= 0) { ____________________ // ← add one to the count }}System.out.println(count);This loop goes over abc. What does the box backwards hold after the loop has run its line twice, for a and then for b?
word = "abc"backwards = ""for ch in word: backwards = ch + backwardsprint(backwards)cba
String word = "abc";String backwards = "";for (char ch : word.toCharArray()) { backwards = ch + backwards;}System.out.println(backwards);cba
Honesty notes
- Go through a string one character at a time with a loop.
- Count the characters that pass a test, with a running count.
- Check a rule on text, such as whether a password contains a digit.
- Build the reverse of a string with a loop, and check whether a word reads the same backwards.