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
Happy coding ;)
Example:
Input string: I love programming.
Input character: o
Output: 9
Required knowledge:
Basic C programming, If else, Loop, Array, StringProgram:
/**
* 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 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 find length of a String.
- C program to compare two strings.
- C program to copy two strings.
- C program to concatenate two strings.
- C program to count total number of alphabets, digits or special characters in the string.
- C program to count total number of vowels and consonants in a string.
- C program to count total number of words in a string.
- C program to find reverse of a String.
- C program to check whether a string is palindrome or not.