Section 9.8 String Iteration
Subsection 9.8.1 A loop for strings
By combining
size
and at()
, we can write a loop that iterates through the characters of a string:
The loop counts from 0 to
size() - 1
(note that we use < size()
in the test). For each of those values, it asks for the character at that index and then prints it. Notice that the counter for this loop is of type size_t
. If we try to make it an int
, the compiler will likely produce an error or warning when we try to compare it to size()
, which is a size_t
. Comparing signed numbers - those that can hold negative numbers like int
- with unsigned values - those that can only hold positive values like size_t
- can produce confusing results.
We could use the same basic loop to modify each character. This program encrypts the string
myString
(very poorly) by shifting each character by 1 alphabetically:
Subsection 9.8.2 The ranged-based for loop
If we are doing something like printing each character in a string, we donβt actually care about which character is at which index. We just want to do something to each character (print it). There is a syntax to make that easier known as the range-based for loop or enhanced for loop:
for (char c : myString) {
// use c
}
You should read that loop as βfor each character, call it c, in myString, do...β The range-based for loop automatically counts through the characters one by one. For each iteration of the loop, the next character is stored into the character variable declared in the loop. In that example, the character is named
c
, but you can name it anything you like. Then, in the loop, you can use that character variable to access the βcurrent letterβ. This example uses the ranged-based loop to count the number of spaces in a string:
There are some limitations to the ranged-based loop that mean it is not always the best option:
-
You donβt know the index of the item you are working with
-
Changing the character you are working with does not change the string itself
There is a syntax for allowing changes to the character variable to also change the string. We will cover that syntax later in SectionΒ 10.5 For now, if you care about the location of each character, or if you need to change the string as you iterate through it, you should not use a range-based loop.
There is no reason you ever have to use the ranged-based loops, you always can use a regular counting loop that counts from 0 to
size() - 1
and index into the string. But the syntax is so simple you likely will want to make use of them.
Checkpoint 9.8.2.
You have attempted of activities on this page.