This tutorial will discuss about unique ways to check if char array is empty in C++.
Table Of Contents
Technique 1: By checking the first character of Char Array
A char array in C++, usually contains a string. Like this,
char arr[50] = “Some text";
The string will always be null terminated. It means the last character of string will be ‘\0’. For example, in the case of string “Some text”, it has 10 characters. First 9 characters are from ‘S’ till ‘t’, and the last character is ‘\0’. So, to check if a char array is empty, we can check if the first character of string is a null terminated character i.e. ‘\0’. If yes, then it means that the char array is empty.
Let’s see the complete example,
#include <iostream> int main() { char arr[10] = {'#include <iostream> int main() { char arr[10] = {'\0'}; // Check if char array is empty if(arr[0] == '\0') { std::cout<<"Char Array is empty. \n"; } else { std::cout<<"Char Array is not empty. \n"; } return 0; }'}; // Check if char array is empty if(arr[0] == '#include <iostream> int main() { char arr[10] = {'\0'}; // Check if char array is empty if(arr[0] == '\0') { std::cout<<"Char Array is empty. \n"; } else { std::cout<<"Char Array is not empty. \n"; } return 0; }') { std::cout<<"Char Array is empty. \n"; } else { std::cout<<"Char Array is not empty. \n"; } return 0; }
Output :
Char Array is empty.
Technique 2: Using strcmp() function
We can use the strcmp()
function to compare a Char Array with an empty string. If it returns 0, then it means that the Char Array is empty.
Frequently Asked:
- Check if two char arrays are equals in C++
- Get the length of char array in C++
- Check if Char Array contains a string in C++
- Convert Char Array to Double or Number in C++
The strcmp()
function accepts two char pointers (strings) as arguments, and returns 0, if both the strings are equal. So, we can use the strcmp()
function to check if a Char Array is empty or not, by comparing it with an empty string.
Let’s see the complete example,
#include <iostream> #include <string.h> int main() { char arr[10] = {'#include <iostream> #include <string.h> int main() { char arr[10] = {'\0'}; // Check if char array is empty if (strcmp(arr, "") == 0) { std::cout<<"Char Array is empty. \n"; } else { std::cout<<"Char Array is not empty. \n"; } return 0; }'}; // Check if char array is empty if (strcmp(arr, "") == 0) { std::cout<<"Char Array is empty. \n"; } else { std::cout<<"Char Array is not empty. \n"; } return 0; }
Output :
Char Array is empty.
Summary
Today we learned about several ways to check if char array is empty in C++. Thanks.