Date: 2008jun27
Update: 2026sep30
Language: C/C++
Q. C/C++: Best way to check if a std::string is all space characters
A. This function does it nicely:
static const char *s_szWhitespaceChars = " \t\r\n";
bool isStdStringAllSpace(const std::string &str) {
if (str.empty()) return true;
return str.find_first_not_of(s_szWhitespaceChars) == std::string::npos;
}
Full Example Use:
#include <stdio.h>
#include <string>
// (Place function isStdStringAllSpace() from above here)
int main() {
{ // With some embedded spaces
std::string str = "o n e";
bool b = isStdStringAllSpace(str);
printf("String '%s' is all space=%s\n", str.c_str(), b ? "yes" : "no");
}
{ // With only a tab
std::string str = "\t";
bool b = isStdStringAllSpace(str);
printf("String <tab> is all space=%s\n", b ? "yes" : "no");
}
{ // Test with empty string
std::string str;
bool b = isStdStringAllSpace(str);
printf("String <empty> is all space=%s\n", b ? "yes" : "no");
}
}
Output:
String 'o n e' is all space=no
String <tab> is all space=yes
String <empty> is all space=yes