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

2021-12-12 00:00:00 string parsing startswith substring c++

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

How do I implement the following (Python pseudocode) in C++?

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

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

(For example, if argv[1] is --foo=98, then foo_value is 98.)

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

Update: I'm hesitant to look into Boost, since I'm just looking at making a very small change to a simple little command-line tool (I'd rather not have to learn how to link in and use Boost for a minor change).

推荐答案

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

Use rfind overload that takes the search position pos parameter, and pass zero for it:

std::string s = "tititoto";
if (s.rfind("titi", 0) == 0) { // pos=0 limits the search to the prefix
  // s starts with prefix
}

谁还需要什么?纯 STL!

Who needs anything else? Pure STL!

许多人误读了这意味着在整个字符串中向后搜索以查找前缀".这将给出错误的结果(例如 string("tititito").rfind("titi") 返回 2,因此当与 ==0 相比时将返回 false)它会效率低下(查看整个字符串,而不仅仅是开头).但它不会这样做,因为它将 pos 参数作为 0 传递,这将搜索限制为仅在该位置或更早匹配.例如:

Many have misread this to mean "search backwards through the whole string looking for the prefix". That would give the wrong result (e.g. string("tititito").rfind("titi") returns 2 so when compared against == 0 would return false) and it would be inefficient (looking through the whole string instead of just the start). But it does not do that because it passes the pos parameter as 0, which limits the search to only match at that position or earlier. For example:

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)

相关文章