How to extract the number from the end of a string in C++

1 Answer

0 votes
#include <iostream>
#include <string>

int extractLastNumber(const std::string& str) {
    int i = str.length();

    while (i > 0 && std::isdigit(str[i - 1])) {
        i--;
    }

    return std::stoi(str.substr(i));
}

int main() {
    std::string str = "java 84 programming8710";

    int n = extractLastNumber(str);

    std::cout << n << std::endl;
}



/*
run:

8710

*/

 



answered Aug 17, 2024 by avibootz

Related questions

1 answer 117 views
2 answers 128 views
2 answers 130 views
2 answers 129 views
2 answers 137 views
2 answers 124 views
...