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.

Required knowledge

Basic C programming, C for loop, Array, functions, Strings

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++;
        }
    }
}



Output:
Enter any string: c programming
Enter character to remove from string: m
String after removing last 'm' : c programing
Process returned 0 (0x0) execution time : 218.210 s



Instagram