c++ string find last number

To find the last number in a C++ string, you can follow these steps:

Step 1: Declare a string variable and initialize it with the desired string.

Step 2: Find the position of the last digit in the string using the rfind() function. The rfind() function searches for a given character from the end of the string and returns its position.

Step 3: Extract the last number from the string using the substr() function. The substr() function takes two arguments: the starting position and the length of the substring to be extracted. In this case, the starting position will be the position of the last digit obtained from step 2, and the length will be the remaining characters until the end of the string.

Step 4: Convert the extracted substring into a numerical value if required using functions like stoi() or atof().

Here is an example of how you can implement these steps in C++:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello123World456";

    // Step 2: Find the position of the last digit
    size_t lastDigitPos = str.rfind("0123456789");

    if (lastDigitPos != std::string::npos) {
        // Step 3: Extract the last number
        std::string lastNumber = str.substr(lastDigitPos);

        // Step 4: Convert the extracted substring to a numerical value
        int number = std::stoi(lastNumber);

        std::cout << "Last number: " << number << std::endl;
    } else {
        std::cout << "No number found." << std::endl;
    }

    return 0;
}

In this example, the string "Hello123World456" is used as an input. The code finds the position of the last digit, which is 14. Then it extracts the substring from position 14 until the end of the string, resulting in "456". Finally, it converts the extracted substring into the numerical value 456 and prints it as the last number.