Check if a String is Empty in C

In C, we can check if a string is empty using various methods, such as checking the first character, using the strlen() function, or comparing it with an empty string.

In this tutorial, we will explore different ways to determine if a string is empty with examples.


Examples to Check if a String is Empty

1. Checking the First Character

In this example, we check if a string is empty by verifying if the first character is the null character ('\0').

main.c

</>
Copy
#include <stdio.h>

int main() {
    char str[] = "";

    // Check if the string is empty by checking the first character
    if (str[0] == '\0') {
        printf("The string is empty.\n");
    } else {
        printf("The string is not empty.\n");
    }

    return 0;
}

Explanation:

  1. We declare a character array str and initialize it as an empty string.
  2. We check if the first character of str is '\0', which indicates that the string is empty.
  3. If str[0] == '\0', we print "The string is empty.".
  4. Otherwise, we print "The string is not empty.".

Output:

The string is empty.

2. Using the strlen() Function

In this example, we use the strlen() function from string.h to check if the string length is zero.

main.c

</>
Copy
#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "";

    // Check if string length is zero
    if (strlen(str) == 0) {
        printf("The string is empty.\n");
    } else {
        printf("The string is not empty.\n");
    }

    return 0;
}

Explanation:

  1. We include string.h to use the strlen() function.
  2. We declare an empty string str.
  3. We call strlen(str) to get the length of the string.
  4. If the length is zero, we print "The string is empty.".
  5. Otherwise, we print "The string is not empty.".

Output:

The string is empty.

3. Comparing with an Empty String

In this example, we compare the string with an empty string using strcmp() from string.h.

main.c

</>
Copy
#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "";

    // Compare string with an empty string
    if (strcmp(str, "") == 0) {
        printf("The string is empty.\n");
    } else {
        printf("The string is not empty.\n");
    }

    return 0;
}

Explanation:

  1. We include string.h to use the strcmp() function.
  2. We declare an empty string str.
  3. We compare str with an empty string "" using strcmp().
  4. If the result is 0, the strings are equal, meaning str is empty.
  5. If not, we print "The string is not empty.".

Output:

The string is empty.

Conclusion

In this tutorial, we explored different ways to check if a string is empty in C:

  1. Checking the first character: Efficient and straightforward.
  2. Using strlen(): Measures the string length and checks if it is zero.
  3. Comparing with an empty string: Uses strcmp() to compare two strings.