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.

Example:
Input string: I love programming.
Input character: o
Output: 9

Required knowledge

Basic C programming, If else, Loop, Array, String

Program 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


Note: Last occurrence of the characters are represented by the zero based index.


Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment