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 in C.
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++.