我刚刚和一个朋友讨论了检查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;
}我正在寻找关于这段代码的反馈,也欢迎更有效的方式来执行这项任务。
发布于 2011-06-23 02:51:44
if(str.find_first_not_of(' ') != std::string::npos)
{
// There's a non-space.
}发布于 2013-08-15 03:20:48
在C++11中,可以使用all_of算法:
// Check if s consists only of whitespaces
bool whiteSpacesOnly = std::all_of(s.begin(),s.end(),isspace);发布于 2011-06-23 02:54:57
为什么这么多工作,这么多打字?
bool has_only_spaces(const std::string& str) {
return str.find_first_not_of (' ') == str.npos;
}https://stackoverflow.com/questions/6444842
复制相似问题