How to check if C string is empty

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

    It is very simple. check for string empty condition in while condition.

    1. You can use strlen function to check for the string length.

      #include
      #include    
      
      int main()
      {
          char url[63] = {'\0'};
          do
          {
              printf("Enter a URL: ");
              scanf("%s", url);
              printf("%s", url);
          } while (strlen(url)<=0);
          return(0);
      }
      
    2. check first character is '\0'

      #include     
      #include 
      
      int main()
      {        
          char url[63] = {'\0'};
      
          do
          {
              printf("Enter a URL: ");
              scanf("%s", url);
              printf("%s", url);
          } while (url[0]=='\0');
      
          return(0);
      }
      

    For your reference:

    C arrays:
    https://www.javatpoint.com/c-array
    https://scholarsoul.com/arrays-in-c/

    C strings:
    https://www.programiz.com/c-programming/c-strings
    https://scholarsoul.com/string-in-c/
    https://en.wikipedia.org/wiki/C_string_handling

提交回复
热议问题