How to check if length of a string is equal to the number appended at its end in C

1 Answer

0 votes
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h> 
#include <stdbool.h>

// long int strtol(const char *str, char **endptr, int base)

bool string_lenght_equal_to_number_at_end(char *str) {
    char *p = str;
    long chcounter = 0, number;
    
    while (*p) { 
        if (isdigit(*p) || ((*p == '-' || *p == '+') && isdigit(*(p + 1)))) {
            number = strtol(p, &p, 10); 
        } else {
            chcounter++;
            p++;
        }
    }
    return chcounter == number;
    
}

int main() {
    char *str = "c programming13";

    puts(string_lenght_equal_to_number_at_end(str) ? "yes" : "no");

    return 0;
}




/*
run:

yes

*/

 



answered Aug 28, 2023 by avibootz
...