How to check if C string is empty

后端 未结 12 1151
一个人的身影
一个人的身影 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:33

    The shortest way to do that would be:

    do {
        // Something
    } while (*url);
    

    Basically, *url will return the char at the first position in the array; since C strings are null-terminated, if the string is empty, its first position will be the character '\0', whose ASCII value is 0; since C logical statements treat every zero value as false, this loop will keep going while the first position of the string is non-null, that is, while the string is not empty.

    Recommended readings if you want to understand this better:

    • C strings: https://www.tutorialspoint.com/cprogramming/c_strings.htm
    • C arrays: https://www.tutorialspoint.com/cprogramming/c_arrays.htm
    • Relation between arrays and pointers: https://www.programiz.com/c-programming/c-pointers-arrays
    • Logical operators: https://www.tutorialspoint.com/cprogramming/c_logical_operators.htm

提交回复
热议问题