我如何在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)
其他回答
if(boost::starts_with(string_to_search, string_to_look_for))
intval = boost::lexical_cast<int>(string_to_search.substr(string_to_look_for.length()));
这是完全未经测试的。原理与Python相同。需要提高。StringAlgo和boost。lexicalcast。
检查字符串是否以另一个字符串开头,然后获取第一个字符串的子字符串('slice')并使用词法转换。
你会这样做:
std::string prefix("--foo=");
if (!arg.compare(0, prefix.size(), prefix))
foo_value = std::stoi(arg.substr(prefix.size()));
寻找一个库,如Boost。为你做这件事的ProgramOptions也是一个好主意。
使用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)
我使用std::string::compare包装在实用方法如下:
static bool startsWith(const string& s, const string& prefix) {
return s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0;
}
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"});