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)
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)
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)
不是更容易做到:
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)
这样做的好处是,一旦找到非空格字符就可以提前返回,因此它比检查整个字符串的解决方案更有效.
要检查字符串在 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)
| 归档时间: |
|
| 查看次数: |
40395 次 |
| 最近记录: |