Write a C program to input any string from user and find the last occurrence of a given character in the string. How to find the last occurrence of a given character in the string. Logic to find last occurrence of a given character in a string in C program.
Example
Input
Input string: I love Codeforwin. Input character to search: o
Output
Last index of 'o' is 12.
Required knowledge
Basic C programming, If else, Loop, String, Functions
Must know – Program to find first occurrence of a character in a string
Logic to find last occurrence of a character in a given string
Logic to find last occurrence of a character is almost similar to finding first occurrence of a character. Just in case of finding last occurrence, we need to iterate till end of string even if the character is found.
Below is the step by step descriptive logic to get last index of a character in a given string.
- Input string from user, store it in some variable say str.
- Declare a index = -1 variable to store matched index of character in given string.
- Run a loop from start character of the string to end character.
- Check if current character is matched with the search character. If match is found then update the index variable with current character index.
- Finally, after loop you will be left with last index of given character.
Program to find last occurrence of character in string
/**
* C program to find last occurrence of a character in string
*/
#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
/* Function declaration */
int lastIndexOf(const char * str, const char toFind);
int main()
{
char str[MAX_SIZE];
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: I love Codeforwin. Enter any character to find: o Last index of o is 12
Happy coding 😉
Recommended posts
- String programming exercises and solutions.
- 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.