I know how to convert a complete string into integer(using std::stoi
). But can you guide me how to extract integer from a string. For example, I want to extract the integer 15
from string a15a
.
string x="a15a";
int a = std::stoi(x);
This above method works fine if the integer is at the start of the string. For example, If the value of string x
is "15a"
, it converts it into integer the 15
. But it does not work if integer is present somewhere in the middle of the string. How to extract an integer from in between the string.
Thanks.
With C++17 you can use std::from_chars to extract a numeric value from a sequence of characters. You code would look something like:
std::string x = "a15a";
int a = 0; // initialize with some value in case parsing fails
std::from_chars(&x[1], &x[3], a); // parse from [first, last) range of chars
Note that I've omitted error checking. Read that link to see how to use the return value from the function.
Another way: You could replace non-digits with spaces so as to use stringstring
extraction of the remaining integers directly:
std::string x = "15a16a17";
for (char &c : x)
{
if (!isdigit(c))
c = ' ';
}
int v;
std::stringstream ss(x);
while (ss >> v)
std::cout << v << "\n";
Output:
15
16
17
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With