by Sai gowtham

How to check if a string is empty in C

In this tutorial, we are going to learn about how to check if a C string is empty or not using the strlen() function.

Checking the empty string

To check if a given string is empty or not, we can use the strlen() function.

The strlen() function takes the string as an argument and returns the total number of characters in a given string, so if that function returns 0 then the given string is empty else it is not empty.

Here is an example:

#include <stdio.h>
#include <string.h>

int main()
{
    char str[] = "";

    if(strlen(str) == 0){
        printf("string is empty");
    }else{
         printf("string is not  empty");
    }

    return 0;
}

Second way

In C language strings are terminated with a null character \0, so we can check if a given string is empty or not by verifying if a string contains the first character is \0.

#include <stdio.h>
#include <string.h>

int main()
{
    char str[] = "";

    if(str[0] == '\0'){
        printf("string is empty");
    }else{
         printf("string is not  empty");
    }

    return 0;
}

Note: C language doesn’t have any built-in function to check if a string is empty, like we have a empty() function in C++.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course