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).
Using STL this could look like:
Since C++11 also std::regex_search can be used, e.g. as follows (returns an empty string on failure):
With C++17 you can use
std::basic_string_view
& with C++20std::basic_string::starts_with
orstd::basic_string_view::starts_with
.The benefit of
std::string_view
in comparison tostd::string
- regarding memory management - is that it only holds a pointer to a "string" (contiguous sequence of char-like objects) and knows its size. Example without moving/copying the source strings just to get the integer value:At the risk of being flamed for using C constructs, I do think this
sscanf
example is more elegant than most Boost solutions. And you don't have to worry about linkage if you're running anywhere that has a Python interpreter!Here's some example output that demonstrates the solution handles leading/trailing garbage as correctly as the equivalent Python code, and more correctly than anything using
atoi
(which will erroneously ignore a non-numeric suffix).Given that both strings —
argv[1]
and"--foo"
— are C strings, @FelixDombek's answer is hands-down the best solution.Seeing the other answers, however, I thought it worth noting that, if your text is already available as a
std::string
, then a simple, zero-copy, maximally efficient solution exists that hasn't been mentioned so far:And if foo is already a string:
Ok why the complicated use of libraries and stuff? C++ String objects overload the [] operator, so you can just compare chars.. Like what I just did, because I want to list all files in a directory and ignore invisible files and the .. and . pseudofiles.
It's that simple..