检查std :: string是否只有空格的有效方法

kar*_*lip 35 c++ string optimization whitespace

我刚刚和朋友讨论了检查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;
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找有关此代码的反馈,也欢迎更有效的方法来执行此任务.

Mar*_*k B 86

if(str.find_first_not_of(' ') != std::string::npos)
{
    // There's a non-space.
}
Run Code Online (Sandbox Code Playgroud)

  • @peterchen要模拟[isspace()](http://www.cplusplus.com/reference/clibrary/cctype/isspace/),您可以发送一个字符串作为参数,例如`str.find_first_not_of("\ t \n \n\v\f\r")!= std :: string :: npos`忽略空格,制表符,换行符,垂直制表符,Feed和回车符. (14认同)
  • 根据实际目的,这可能需要是`isspace()`而不是硬编码`'' (6认同)

Mic*_*eyn 45

在C++ 11中,all_of可以使用该算法:

// Check if s consists only of whitespaces
bool whiteSpacesOnly = std::all_of(s.begin(),s.end(),isspace);
Run Code Online (Sandbox Code Playgroud)

  • 如果gcc给你以下错误:"模板参数扣除/替换失败:无法推断模板参数'_Predicate'" - 请参阅:http://stackoverflow.com/questions/21578544/stdremove-if-and-stdisspace-compile - 时间错误 (9认同)
  • @Sundae 有两个 isspace() 函数,一个来自 &lt;cctype&gt; 是我们在这里需要的,而另一个来自 &lt;locale&gt; 不是。解决它的方法是使用 ::isspace 作为谓词。 (3认同)

Dav*_*men 15

为什么这么多工作,打字这么多?

bool has_only_spaces(const std::string& str) {
   return str.find_first_not_of (' ') == str.npos;
}
Run Code Online (Sandbox Code Playgroud)


Tom*_*Tom 6

不是更容易做到:

bool has_only_spaces(const std::string &str)
{
    for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
    {
        if (*it != ' ') return false;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

这样做的好处是,一旦找到非空格字符就可以提前返回,因此它比检查整个字符串的解决方案更有效.

  • 我能想到的唯一可能的低级优化是比较寄存器宽度的块,例如x86上每次4字节,并与0x20202020进行比较.但那太疯狂了. (2认同)

eri*_*tin 5

要检查字符串在 c++11 中是否只有空格:

bool is_whitespace(const std::string& s) {
  return std::all_of(s.begin(), s.end(), isspace);
}
Run Code Online (Sandbox Code Playgroud)

在 C++11 之前:

bool is_whitespace(const std::string& s) {
  for (std::string::const_iterator it = s.begin(); it != s.end(); ++it) {
    if (!isspace(*it)) {
      return false;
    }
  }
  return true;
}
Run Code Online (Sandbox Code Playgroud)