我刚刚和一位 friend 讨论了检查 std::string 是否只有空格的最有效方法。他需要在他正在从事的嵌入式项目上执行此操作,显然这种优化对他很重要。
我想出了以下代码,它使用 strtok()
。
bool has_only_spaces(std::string& str)
{
char* token = strtok(const_cast<char*>(str.c_str()), " ");
while (token != NULL)
{
if (*token != ' ')
{
return true;
}
}
return false;
}
我正在寻找有关此代码的反馈,也欢迎更有效的方法来执行此任务。
最佳答案
if(str.find_first_not_of(' ') != std::string::npos)
{
// There's a non-space.
}
关于c++ - 检查 std::string 是否只有空格的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6444842/