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
Getting Started with Express
Create an RSS Reader in Node
Git Tutorial: Learn how to use Version Control
Getting Started with Deno
How to deploy a MySQL Server using Docker
How to deploy a Node app using Docker
Getting Started with Sass
How to Scrape the Web using Node.js and Puppeteer
Getting Started with Handlebars.js
Getting User Location using JavaScript's Geolocation API
Learn how to build a Slack Bot using Node.js
