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!
- Managing PHP Dependencies with Composer
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with React
- Setting Up Stylus CSS Preprocessor