How to check if length of a string is equal to the number appended at its end 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;
}

bool string_lenght_equal_to_number_at_end(std::string str) {
    int size = str.size();
    long chcounter = 0;
    
    for (int i = 0; i < size; i++) {
        if ( ! isdigit(str[i])) {
            chcounter++;
        }
    }

    return chcounter == extract_last_number_from_string(str);
     
}

 
int main() {
    std::string str = "c++ programming15";

    std::cout << (string_lenght_equal_to_number_at_end(str) ? "yes" : "no");
}
 
 
 
 
 
/*
run:
 
yes
 
*/

 



answered Aug 29, 2023 by avibootz
...