Check if a String is Empty or Whitespaces only
The following C++ function is a small utility that checks if a string is empty (null) or if it consists of only whitespaces.
bool IsEmptyOrWhitespace(const std::string& str) {
return str.empty() || std::all_of(str.begin(), str.end(), isspace);
}Given the string str, the function returns true if it's empty (null) or if it consists of only whitespaces.
The following code block demonstrates a use case:
#include <algorithm>
#include <iostream>
bool IsEmptyOrWhitespace(const std::string& str) {
return str.empty() || std::all_of(str.begin(), str.end(), isspace);
}
int main() {
const char* name = " ";
if (IsEmptyOrWhitespace(name)) {
std::cout << "Empty or whitespace only!" << std::endl;
} else {
std::cout << "[" << name << "]" << std::endl;
}
return 1;
}Output:
Empty or whitespace only!