C program to remove last occurrence of a character from the string

Write a C program to read any string from user and remove last occurrence of a given character from the string. How to remove the last occurrence of a character from string in C programming. Logic to remove last occurrence of a character from the string.

Example

Input

Input string : I love programming. I love Codeforwin.
Input character to remove : 'I'

Output

String after removing last 'I' : I love programming. love Codeforwin.

Required knowledge

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

Must know –

Logic to remove last occurrence of a character

Below is the step by step descriptive logic to remove last occurrence of a character in given string.

  1. Input string from user, store it in some variable say str.
  2. Input character to remove from user, store it in some variable say toRemove.
  3. Find last occurrence of the given character toRemove in str.
  4. From the last occurrence of given character in string, shift next characters one place to its left.

Program 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 string size

/* Function declaration */
void removeLast(char *, const char);


int main()
{
    char str[MAX_SIZE];
    char toRemove;

    printf("Enter any string: ");
    gets(str);

    printf("Enter character to remove from string: ");
    toRemove = getchar();

    removeLast(str, toRemove);

    printf("String after removing last '%c' : %s", toRemove, str);

    return 0;
}


/**
 * Function to remove last occurrence of a character from the string.
 */
void removeLast(char * str, const char toRemove)
{
    int i, lastPosition;
    int len = strlen(str);

    /* Assume that character does not exist in string */
    lastPosition = -1;
    i=0;

    while(i<len)
    {
        if(str[i] == toRemove)
        {
            lastPosition = i;
        }

        i++;
    }

    /* If character exists in string */
    if(lastPosition != -1)
    {
        i = lastPosition;

        /*
         * Shift all characters right to the position found above to left
         */
        while(i<len)
        {
            str[i] = str[i+1];
            i++;
        }
    }
}

Read more – Program to remove first occurrence of a given character in string

Output

Enter any string: I love programming. I love Codeforwin.
Enter character to remove from string: I

String after removing last 'I' : I love programming. love Codeforwin.

Happy coding 😉