Checking Prefix and Extracting Numeric Substring in C
In Python, checking if a string starts with a specific prefix and converting a substring to an integer is a straightforward task. However, in C , it may not be immediately apparent how to achieve similar functionality.
To determine if a string starts with a certain substring, we can utilize the rfind function with the pos parameter set to zero. This ensures the search is confined to the beginning of the string. For instance:
<code class="cpp">std::string str = "tititoto"; if (str.rfind("titi", 0) == 0) { // The string starts with "titi" }</code>
In the above example, pos is set to zero, which limits the search to the prefix. Hence, rfind returns 0 if the string commences with the specified substring. Otherwise, it returns std::string::npos, indicating failure.
With C 20 and later, the process becomes simpler due to the introduction of starts_with in std::string and std::string_view.
<code class="cpp">std::string str = "tititoto"; if (str.starts_with("titi")) { // The string starts with "titi" }</code>
To extract a numeric substring from a string, we can use std::stoi. For example, if we have a string such as "--foo=98", we can extract the numeric value as follows:
<code class="cpp">std::string arg = "--foo=98"; std::size_t pos = arg.find("--foo="); if (pos != std::string::npos) { std::string foo = arg.substr(pos + sizeof("--foo=") - 1); int foo_value = std::stoi(foo); }</code>
In this case, we use find to locate the position of the "--foo=" prefix. If found, we extract the substring using substr and convert it to an integer using std::stoi.
These techniques provide efficient and concise solutions for working with strings in C .
The above is the detailed content of How Can I Check for Prefixes and Extract Numeric Substrings in C ?. For more information, please follow other related articles on the PHP Chinese website!