How to Check if a String is Empty in C

Updated onbyAlan Morel
How to Check if a String is Empty in C

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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.