Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 7, 2022 10:03 am GMT

How To Iterate Over C String

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 parenthesis 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.


Original Link: https://dev.to/zirkelc/how-to-iterate-over-c-string-lcj

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To