Quantcast
Channel: Codeforwin
Viewing all articles
Browse latest Browse all 132

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

$
0
0
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:


/**
* 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
X
_
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 ;)



Viewing all articles
Browse latest Browse all 132

Trending Articles