How to check if a string is blank (empty, null, or contains only whitespace) in C++

1 Answer

0 votes
#include <algorithm>
#include <iostream>
#include <string>
#include <cctype>

bool isBlank(const std::string* str) {
    // Check for null pointer
    if (str == nullptr) {
        return true;
    }

    // Check if the string is empty or contains only whitespace
    return str->empty() || std::all_of(str->begin(), str->end(), [](unsigned char ch) { 
        return std::isspace(ch); });
}

int main() {
    std::string test1 = "";     // Empty string
    std::string test2 = "   ";  // Whitespace only
    std::string* test3 = nullptr; // NULL string pointer
    std::string test4 = "C++";  // Non-empty string

    std::cout << std::boolalpha; // Print boolean values as true/false
    std::cout << "Test1 is blank: " << isBlank(&test1) << std::endl;
    std::cout << "Test2 is blank: " << isBlank(&test2) << std::endl;
    std::cout << "Test3 is blank: " << isBlank(test3) << std::endl;
    std::cout << "Test4 is blank: " << isBlank(&test4) << std::endl;
}



/*
run:

Test1 is blank: true
Test2 is blank: true
Test3 is blank: true
Test4 is blank: false

*/

 



answered Jun 7, 2025 by avibootz
...