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).
The string class in C++ has a member function called start_with(). It checks if a sub-independent string, forms the first characters of a string of interest (prefix). The overloaded member functions are starts_with(charT x), starts_with(const charT* x), and starts_with(string_view x). Each returns a bool.
Getting the first character To access the first character of a string, we can use the subscript operator [ ] by passing an index 0 . Note: In C++ Strings are a sequence of characters, so the first character index is 0 and the second character index is 1, etc.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With