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

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

$
0
0
Write a C program to read any string from user and remove the last occurrence of a given character from the string. This program should also use the concepts of functions to remove the last occurrence of character from the string. How to remove the last occurrence of a character from string in C programming.

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, Functions

Program:


/**
* C program to remove last occurrence of a character from the given string.
*/

#include <stdio.h>
#include <string.h>

#define MAX_SIZE 100



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



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

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

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

removeLast(text, toRemove);

printf("\nOutput : %s", text);

return 0;
}



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

lastPosition = -1;
i=0;

while(i<len)
{
if(text[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)
{
text[i] = text[i+1];
i++;
}
}

/* Make the last character null */
text[i] = '\0';
}



Output
X
_
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.

Happy coding ;)



Viewing all articles
Browse latest Browse all 132

Trending Articles