C Strings and Loops
Loop Through a String
You can also loop through the characters of a string,
using a for
loop:
Example
char carName[] = "Volvo";
int i;
for (i = 0; i < 5; ++i) {
printf("%c\n", carName[i]);
}
Try it Yourself »
Instead of writing the length of the string in the loop condition (i < 5), you can use the strlen() function.
It returns the number of characters in a string, and it is part of the <string.h> header file (you will learn more about it in the String Functions chapter):
Example
char carName[] = "Volvo";
int length = strlen(carName);
int i;
for (i = 0; i < length; ++i) {
printf("%c\n", carName[i]);
}
Try it Yourself »
Note: The sizeof formula from the Array Loops chapter does not work as well for strings. sizeof also counts the \0 character at the end of the string (see The Null Character), so it gives 6 for "Volvo" instead of 5.