我如何在c++中实现以下(Python伪代码)?

if argv[1].startswith('--foo='):
    foo_value = int(argv[1][len('--foo='):])

(例如,如果argv[1]是——foo=98,那么foo_value是98。)

更新:我很犹豫是否要研究Boost,因为我只是想对一个简单的小命令行工具做一个非常小的改变(我宁愿不学习如何链接并使用Boost进行一个小的改变)。


当前回答

我使用std::string::compare包装在实用方法如下:

static bool startsWith(const string& s, const string& prefix) {
    return s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0;
}

其他回答

如果你已经在使用Boost,你可以使用Boost字符串算法+ Boost词法转换:

#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>

try {    
    if (boost::starts_with(argv[1], "--foo="))
        foo_value = boost::lexical_cast<int>(argv[1]+6);
} catch (boost::bad_lexical_cast) {
    // bad parameter
}

这种方法,就像这里提供的许多其他答案一样,适用于非常简单的任务,但从长远来看,您通常最好使用命令行解析库。Boost有一个(Boost. program_options),如果您碰巧已经在使用Boost,这可能是有意义的。

否则,搜索“c++命令行解析器”会得到许多选项。

你会这样做:

std::string prefix("--foo=");
if (!arg.compare(0, prefix.size(), prefix))
    foo_value = std::stoi(arg.substr(prefix.size()));

寻找一个库,如Boost。为你做这件事的ProgramOptions也是一个好主意。

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"});

为了完整起见,我将提到C的方法:

如果str是你的原始字符串,substr就是你想要的子字符串 检查,然后 Strncmp (str, substr, strlen(substr)) 将返回0如果STR 从substr开始。函数strncmp和strlen在C 头文件<string.h>

(最初由Yaseen Rauf在这里发布,添加了标记)

对于不区分大小写的比较,请使用strnicmp而不是strncmp。

这是C语言的方法,对于c++的字符串,你可以像这样使用相同的函数:

strncmp(str.c_str(), substr.c_str(), substr.size())

假设两个字符串——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());