我如何在c++中实现以下(Python伪代码)?
if argv[1].startswith('--foo='):
foo_value = int(argv[1][len('--foo='):])
(例如,如果argv[1]是——foo=98,那么foo_value是98。)
更新:我很犹豫是否要研究Boost,因为我只是想对一个简单的小命令行工具做一个非常小的改变(我宁愿不学习如何链接并使用Boost进行一个小的改变)。
我如何在c++中实现以下(Python伪代码)?
if argv[1].startswith('--foo='):
foo_value = int(argv[1][len('--foo='):])
(例如,如果argv[1]是——foo=98,那么foo_value是98。)
更新:我很犹豫是否要研究Boost,因为我只是想对一个简单的小命令行工具做一个非常小的改变(我宁愿不学习如何链接并使用Boost进行一个小的改变)。
当前回答
使用rfind重载,接受搜索位置pos参数,并为其传递0:
std::string s = "tititoto";
if (s.rfind("titi", 0) == 0) { // pos=0 limits the search to the prefix
// s starts with prefix
}
谁还需要别的东西?纯STL !
许多人将其误解为“在整个字符串中反向搜索前缀”。这将给出错误的结果(例如string("tititito").rfind("titi")返回2,因此当与== 0进行比较时将返回false),并且它将是低效的(查看整个字符串而不是只查看开头)。但是它没有这样做,因为它将pos参数传递为0,这将搜索限制在该位置或更早的位置进行匹配。例如:
std::string test = "0123123";
size_t match1 = test.rfind("123"); // returns 4 (rightmost match)
size_t match2 = test.rfind("123", 2); // returns 1 (skipped over later match)
size_t match3 = test.rfind("123", 0); // returns std::string::npos (i.e. not found)
其他回答
c++ 20更新:
使用std:: string:: starts_with
https://en.cppreference.com/w/cpp/string/basic_string/starts_with
std::string str_value = /* smthg */;
const auto starts_with_foo = str_value.starts_with(std::string_view{"foo"});
你会这样做:
std::string prefix("--foo=");
if (!arg.compare(0, prefix.size(), prefix))
foo_value = std::stoi(arg.substr(prefix.size()));
寻找一个库,如Boost。为你做这件事的ProgramOptions也是一个好主意。
我使用std::string::compare包装在实用方法如下:
static bool startsWith(const string& s, const string& prefix) {
return s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0;
}
假设两个字符串——argv[1]和"——foo"——都是C字符串,@FelixDombek的答案无疑是最好的解决方案。
然而,看到其他答案,我认为值得注意的是,如果你的文本已经作为std::string可用,那么一个简单的、零拷贝的、最大效率的解决方案存在,到目前为止还没有提到:
const char * foo = "--foo";
if (text.rfind(foo, 0) == 0)
foo_value = text.substr(strlen(foo));
如果foo已经是一个字符串:
std::string foo("--foo");
if (text.rfind(foo, 0) == 0)
foo_value = text.substr(foo.length());
text.substr(0, start.length()) == start