Home > Article > Backend Development > How can I check for string prefixes and convert substrings to integers in C ?
Exact String Matching and Substring Conversion in C
To determine if a C std::string begins with a given string, as in the Python example provided, use the rfind overload that accepts a search position parameter. Here's how:
<code class="cpp">std::string s = "tititoto"; if (s.rfind("titi", 0) == 0) { // pos=0 limits search to the prefix // s starts with the prefix }</code>
C 20 and later introduced the starts_with method, simplifying the process:
<code class="cpp">std::string s = "tititoto"; if (s.starts_with("titi"s)) { // "s" suffix creates a std::string_view // s starts with the prefix }</code>
Now, let's consider the int conversion. In the original Python code, a substring is extracted using the slice notation [len('--foo='):]. To achieve the same in C , use the substr method:
<code class="cpp">std::string argv1 = "--foo=98"; std::string foo_value_str = argv1.substr(argv1.find("=") + 1); int foo_value = std::stoi(foo_value_str);</code>
By using these techniques, you can check for string prefixes and convert substrings to integers efficiently in C .
The above is the detailed content of How can I check for string prefixes and convert substrings to integers in C ?. For more information, please follow other related articles on the PHP Chinese website!