Find the last occurrence of a character in a given string with C.
#include <stdio.h>
/* Function declaration */
int lastIndexOf(const char *str, const char toFind);
int main()
{
char str[100];
char toFind;
int index;
printf("Enter any string: ");
gets(str);
printf("Enter any character to find: ");
toFind = getchar();
index = lastIndexOf(str, toFind);
printf("\nLast index of '%c' is %d", toFind, index);
return 0;
}
///Function to find last index of any character in the given string
int lastIndexOf(const char *str, const char toFind)
{
int index = -1;
int i = 0;
while (str[i] != '\0')
{
// Update index if match is found
if (str[i] == toFind)
{
index = i;
}
i++;
}
return index;
}
Output
Enter any string : learn with reza
Enter any character to find : w
Last index of 'w' is 6
0 Comments