How to iterate over a string in C?

前端 未结 13 1305
花落未央
花落未央 2020-11-28 06:43

Right now I\'m trying this:

#include 

int main(int argc, char *argv[]) {

    if (argc != 3) {

        printf(\"Usage: %s %s sourcecode inpu         


        
13条回答
  •  悲&欢浪女
    2020-11-28 07:17

    An optimized approach:

    for (char character = *string; character != '\0'; character = *++string)
    {
        putchar(character); // Do something with character.
    }
    

    Most C strings are null-terminated, meaning that as soon as the character becomes a '\0' the loop should stop. The *++string is moving the pointer one byte, then dereferencing it, and the loop repeats.

    The reason why this is more efficient than strlen() is because strlen already loops through the string to find the length, so you would effectively be looping twice (one more time than needed) with strlen().

提交回复
热议问题