gpt4 book ai didi

c++ - 如何检查 C++ std::string 是否以某个字符串开头,并将子字符串转换为 int?

转载 作者:IT老高 更新时间:2023-10-28 11:27:30 25 4
gpt4 key购买 nike

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

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

(例如,如果 argv[1]--foo=98,那么 foo_value98.)

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

最佳答案

使用 rfind采用搜索位置 pos 参数的重载,并为其传递零:

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++ - 如何检查 C++ std::string 是否以某个字符串开头,并将子字符串转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1878001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com