Iterating over a string sounds like a simple task, but every time I have to do it, I come across a different way. This will be a collection of different ways and how they work.
Brackets
For-Loop
We determine the length of the string with strlen(str)
and access each character of the string with the bracket str[i]
.
char *str = "This is an example.";
size_t length = strlen(str);
for (size_t i = 0; i < length; i++)
{
printf("%c", str[i]);
}
Remember to place strlen()
outside the for loop condition, otherwise it will be called on each iteration.
While-Loop
We can also avoid determining the length of the string in advance, and simply iterate over the string until we reach the end indicated by a null terminator \0
.
char *str = "This is an example.";
size_t i = 0;
while (str[i] != '\0')
{
printf("%c", str[i]);
i++;
}
Furthermore, the condition of the while loop can be reduced to str[i]
, since any value that is not zero is evaluated as true.
while (str[i])
{
printf("%c", str[i]);
i++;
}
Pointer
For-Loop
Accessing the first character of the string with brackets str[0]
corresponds to *str
and accessing the second character via str[1]
corresponds to *(str+1)
or *++str
. To avoid modifying the original pointer *str
, we copy it to a temporary pointer *p
and increment this pointer at each iteration with *++p
. This is the combination of ++p
and *p
.
char *str = "This is an example.";
char *p = str;
for (char c = *p; c != '\0'; c = *++p)
{
printf("%c", c);
}
While-Loop
This is basically the same as the for loop, but accessing the character with *c
and incrementing the pointer are separated.
char *str = "This is an example.";
char *c = str;
while (*c != '\0')
{
printf("%c", *c);
c++;
}
Since we only print the character with printf()
, we can combine the access and increment into an expression *++c
and pass it to printf()
.
while (*c != '\0')
{
printf("%c", *++c);
}
Similar to the brackets notation, the condition for the while loop can be reduced to *c
.
while (*c)
{
printf("%c", *++c);
}
Discussion
There are probably many more ways to iterate over a C string, and many good reasons for when to choose which implementation. If anyone has another option or comment, I'd be happy to learn it and add it to this post.
Top comments (2)
Hey there!
Thank you for this article, it was really helpfull to see how many ways you can iterate through a string in C.
Recently I was doing my daily Kata in codewars and saw an interesting way to also iterate through a string.
for(; string; *string++) {
// **string is the current character being examined.
}
I just wanted to share this somehow.
Hey @nativixk I'm glad it was helpful.
I wrote this post after finishing my C challenges on HackerRank. It's mindblowing how many ways there are.