请告诉我如何检查给定字符串的第一个单词是否为"echo",忽略单词前是否有空格。
示例:
string hello = " echo hello hihi";
if(startwith(hello, "echo")
{
//some code here
}
如果可能的话,请帮助我
string_view
具有类似的功能。跳过空白处并使用它。
#include <string>
#include <string_view>
using std::string, std::string_view;
constexpr bool StartsWithSkipWs(string_view const str,
string_view const prefix) noexcept {
auto begin = str.find_first_not_of(" tnfrv");
if (begin == string_view::npos) return false;
return str.substr(begin).starts_with(prefix);
}
int main() {
string hello = "echo hello hihi";
if (StartsWithSkipWs(hello, "echo"))
{
// ...
}
}
#include<iostream>
#include<boost/algorithm/string.hpp>
using namespace std;
int main(){
string hello = " echo hello hihi";
boost::trim_left(hello);
string subst=hello.substr(0,4);
if(subst=="echo"){
////some code here
}
}