How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?
Use an overload of rfind
which has the pos
parameter:
std::string s = "tititoto";
if (s.rfind("titi", 0) == 0) {
// 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)
You would do it like this:
std::string prefix("--foo=");
if (!arg.compare(0, prefix.size(), prefix))
foo_value = std::stoi(arg.substr(prefix.size()));
Looking for a lib such as Boost.ProgramOptions that does this for you is also a good idea.
Just for completeness, I will mention the C way to do it:
If
str
is your original string,substr
is the substring you want to check, then
strncmp(str, substr, strlen(substr))
will return
0
ifstr
starts withsubstr
. The functionsstrncmp
andstrlen
are in the C header file<string.h>
(originally posted by Yaseen Rauf here, markup added)
For a case-insensitive comparison, use strnicmp
instead of strncmp
.
This is the C way to do it, for C++ strings you can use the same function like this:
strncmp(str.c_str(), substr.c_str(), substr.size())