Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a part of string into integer?

Tags:

c++

string

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.

like image 792
mango Avatar asked Jan 25 '23 15:01

mango


2 Answers

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.

like image 123
Blastfurnace Avatar answered Jan 30 '23 00:01

Blastfurnace


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
like image 37
acraig5075 Avatar answered Jan 30 '23 00:01

acraig5075