Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 888
Daryl Spitzer Avatar asked Dec 10 '09 00:12

Daryl Spitzer


People also ask

How do you check if a string starts with a substring in C++?

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.

How do you get the first character of a string in C++?

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.


1 Answers

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) 
like image 144
Ludovic Aubert Avatar answered Oct 19 '22 23:10

Ludovic Aubert