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

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

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

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


当前回答

在c++ 20中,starts_with作为std::string的成员函数可用,定义为:

constexpr bool starts_with(string_view sv) const noexcept;

constexpr bool starts_with(CharT c) const noexcept;

constexpr bool starts_with(const CharT* s) const;

所以你的代码可以是这样的:

std::string s{argv[1]};

if (s.starts_with("--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())

使用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结构的风险,我确实认为这个sscanf示例比大多数Boost解决方案更优雅。如果您在任何有Python解释器的地方运行,则不必担心链接!

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    for (int i = 1; i != argc; ++i) {
        int number = 0;
        int size = 0;
        sscanf(argv[i], "--foo=%d%n", &number, &size);
        if (size == strlen(argv[i])) {
            printf("number: %d\n", number);
        }
        else {
            printf("not-a-number\n");
        }
    }
    return 0;
}

下面是一些示例输出,演示了该解决方案与等效的Python代码一样正确地处理前导/尾随垃圾,并且比使用atoi的任何方法都更正确(后者会错误地忽略非数字后缀)。

$ ./scan --foo=2 --foo=2d --foo='2 ' ' --foo=2'
number: 2
not-a-number
not-a-number
not-a-number

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

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