How to check if C string is empty

后端 未结 12 1153
一个人的身影
一个人的身影 2021-01-30 19:41

I\'m writing a very small program in C that needs to check if a certain string is empty. For the sake of this question, I\'ve simplified my code:

#include 

        
12条回答
  •  野的像风
    2021-01-30 20:24

    Since C-style strings are always terminated with the null character (\0), you can check whether the string is empty by writing

    do {
       ...
    } while (url[0] != '\0');
    

    Alternatively, you could use the strcmp function, which is overkill but might be easier to read:

    do {
       ...
    } while (strcmp(url, ""));
    

    Note that strcmp returns a nonzero value if the strings are different and 0 if they're the same, so this loop continues to loop until the string is nonempty.

    Hope this helps!

提交回复
热议问题