How to Check if a String is Empty in C
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!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js