Iterating Over the Characters in a String
suggest changeIf we know the length of the string, we can use a for loop to iterate over its characters:
char * string = "hello world"; /* This 11 chars long, excluding the 0-terminator. */
size_t i = 0;
for (; i < 11; i++) {
printf("%c\n", string[i]); /* Print each character of the string. */
}
Alternatively, we can use the standard function strlen()
to get the length of a string if we don’t know what the string is:
size_t length = strlen(string);
size_t i = 0;
for (; i < length; i++) {
printf("%c\n", string[i]); /* Print each character of the string. */
}
Finally, we can take advantage of the fact that strings in C are guaranteed to be null-terminated (which we already did when passing it to strlen()
in the previous example ;-)). We can iterate over the array regardless of its size and stop iterating once we reach a null-character:
size_t i = 0;
while (string[i] != '\0') { /* Stop looping when we reach the null-character. */
printf("%c\n", string[i]); /* Print each character of the string. */
i++;
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents