How to check if a string ends with a specified substring in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

int endswith(const char* haystack, const char* needle) {
    size_t haystacklen = strlen(haystack);
    size_t needlelen = strlen(needle);

    if (needlelen > haystacklen) return 0;

    // end of haystack equals needle ?

    return strcmp(&haystack[haystacklen - needlelen], needle) == 0;
}

int main() {

    char s[] = "c c++ java python";
    char tofind[] = "python";

    if (endswith(s, tofind)) {
        printf("Yes\n");
    }
    else {
        printf("No\n");
    }

    return 0;
}



/*
run:

yes

*/

 



answered May 25, 2024 by avibootz
edited May 25, 2024 by avibootz

Related questions

1 answer 110 views
2 answers 104 views
1 answer 139 views
1 answer 175 views
1 answer 168 views
1 answer 224 views
...