C program to find last occurrence of a character in a string

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.

  1. Input string from user, store it in some variable say str.
  2. Declare a index = -1 variable to store matched index of character in given string.
  3. Run a loop from start character of the string to end character.
  4. Check if current character is matched with the search character. If match is found then update the index variable with current character index.
  5. 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 😉