Table of Contents
In this post, we're going to learn how you can check if a string is empty or not in C.
Because C does not have a built-in function to check if a string is empty, we have to rely on our own code.
Using strlen()
The best way to check if a string is empty is to use the strlen() function.
This built-in function returns the length of a string when you pass in the string as an argument.
It will naturally return the number of characters in a string, and so to check if it is empty, simply check if the length of the string is 0.
Here's an example of how to use the strlen() function:
CLIKE#include <stdio.h>
#include <string.h>
int main() {
char string[] = "";
if (strlen(string) == 0) {
printf("String is empty");
} else {
printf("String is not empty");
}
return 0;
}
Using null character
Another way you can check if a string is empty is to check if the first character of the string is a null character. In C, a null character is represented by the \0 character, and that character is the last character in a string.
Therefore, if the length of the string is 0, then the first character of the string is a null character.
Let's see an example of how to use this method:
CLIKE#include <stdio.h>
#include <string.h>
int main() {
char string[] = "";
if (string[0] == '\0') {
printf("String is empty");
} else {
printf("String is not empty");
}
return 0;
}
Conclusion
In this post, we saw two different ways in which you can check if a string is empty or not in C. The first method uses the strlen() function, and the second method checks if the first character of the string is a null character.
Hopefully, this has helped you out with your C programming journey.
Happy coding!
Getting Started with Solid
Getting Started with Express
Getting Started with Electron
How to Serve Static Files with Nginx and Docker
How to Set Up Cron Jobs in Linux
How to build a Discord bot using TypeScript
How to deploy a PHP app using Docker
How to deploy a Deno app using Docker
How to deploy an Express app using Docker
Build a Real-Time Chat App with Node, Express, and Socket.io
Setting Up Stylus CSS Preprocessor
Using Axios to Pull Data from a REST API
