How to extract the last number from a string in C++

1 Answer

0 votes
#include <iostream>
#include <sstream>
 
int extract_last_number_from_string(std::string str) {
    size_t last_index = str.find_last_not_of("0123456789");
     
    std::string result = str.substr(last_index + 1);
     
    int n;
    std::stringstream ss(result);
    ss >> n;
     
    return n;
}
 
  
int main() {
    std::string str = "22c++ programming15";
 
    int n = extract_last_number_from_string(str);
     
    std::cout << n;
}
  
  
  
  
  
/*
run:
  
15
  
*/

 



answered Aug 29, 2023 by avibootz
edited Aug 30, 2023 by avibootz

Related questions

1 answer 138 views
1 answer 118 views
2 answers 177 views
1 answer 129 views
1 answer 113 views
...