Example:
Input string : I love programming. I love CodeForWin. I love india.
Input character to remove : 'I'
Output : I love programming. I love CodeForWin. love india.
Required knowledge
Basic C programming, If else, Loop, Array, String, FunctionsProgram to remove last occurrence of character
/**
* C program to remove last occurrence of a character from the given string.
*/
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 //Maximum size of the string
/** Function declaration */
void removeLast(char *, const char);
int main()
{
char string[MAX_SIZE];
char toRemove;
printf("Enter any string: ");
gets(string);
printf("Enter character to remove from string: ");
toRemove = getchar();
removeLast(string, toRemove);
printf("\nOutput : %s", string);
return 0;
}
/**
* Function to remove last occurrence of a character from the string.
*/
void removeLast(char * string, const char toRemove)
{
int i, lastPosition;
int len = strlen(string);
lastPosition = -1;
i=0;
while(i<len)
{
if(string[i] == toRemove)
{
lastPosition = i;
}
i++;
}
if(lastPosition != -1)
{
i = lastPosition;
/*
* Shift all characters right to the position found above to left
*/
while(i<len-1)
{
string[i] = string[i+1];
i++;
}
}
/* Make the last character null */
string[i] = '\0';
}
Output
Enter any string: I love programming. I love CodeForWin. I love india.
Enter character to remove from string: I
Output : I love programming. I love CodeForWin. love india.
Enter character to remove from string: I
Output : I love programming. I love CodeForWin. love india.
Happy coding ;)
You may also like
- String programming exercises index.
- C program to find first occurrence of a given character in string.
- C program to count occurrence of a character in given string.
- C program to remove first 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 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.