Search code examples
c++stringparsingsubstringstartswith

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?


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

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

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

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).


Solution

  • 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
    }
    

    Who needs anything else? Pure STL!

    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)
    

    For C++20 onwards it got way simpler as both std::string and std::string_view has starts_with:

    std::string s = "tititoto";
    if (s.starts_with("titi"s)) {
      // s starts with prefix
    }