Example:
Input string: I love programming.
Input character: o
Output: 9
Required knowledge
Basic C programming, If else, Loop, Array, StringProgram to find last occurrence of character in string
/** * C program to find last occurrence of a character in string */ #include <stdio.h> #include <string.h> #define MAX_SIZE 100 /** Function declaration */ int lastIndexOf(const char * text, const char toFind); int main() { char text[MAX_SIZE]; char toFind; int index; printf("Enter any string: "); gets(text); printf("Enter any character to find: "); toFind = getchar(); index = lastIndexOf(text, 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 * text, const char toFind) { int index = -1; int i, len; len = strlen(text); for(i=0; i<len; i++) { if(text[i] == toFind) { index = i; } } return index; }
Output
Enter any string: I love programming.
Enter any character to find: o
Last index of o is 9
Enter any character to find: o
Last index of o is 9
Note: Last occurrence of the characters are represented by the zero based index.
Happy coding ;)
You may also like
- String programming exercises and solutions.
- C program to find first occurrence of a given character in string.
- C program to count occurrences of a character in string.
- C program to remove first occurrence of a character from the string.
- C program to remove last occurrence of a character from the string.
- C program to remove all occurrences of a character from the string.
- C program to find first occurrence of a given word in string.
- C program to count frequency of each character in a string.
- C program to count total number of alphabets, digits or special characters in the string.
- C program to count total number of words in a string.
- C program to check whether a string is palindrome or not.