How to get the index of the last occurrence of specified character in a string with C

1 Answer

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

int LastIndexOf(char str[], char ch) {
    char* p = strrchr(str, ch);

    if (p)
        return (int)(p - str);

    return -1;
}

int main() {

    char str[] = "c c++ csharp java php python";

    printf("%d\n", LastIndexOf(str, 'c'));

    printf("%d\n", LastIndexOf(str, 'a'));

    printf("%d\n", LastIndexOf(str, 'p'));

    return 0;
}




/*
run:

6
16
22

*/

 



answered Sep 4, 2022 by avibootz
...