Our mission is to learn how to remove character from string in C using Pointer. Let me think how, so we need to write a function that receives a character string (word) and a character as arguments and deletes all occurrences of this character in the string. The function should return the corrected string with no holes.

Example

String entered: database

Character entered: a

Result: dtbse

Algorithm and Logic using Pointer in C Programs.

Firstly, create an array of characters of any size to store a string word, and a variable ch to store choice of users.

char word[150],ch;

On second, ask using enter a string and store string input from user using gets() methods. gets() methods is defined in the header file stdio.h.

gets(word);

After that, ask for user choice to enter the character they want to remove from the string word he just entered and store character in ch.

scanf("%c",&ch);

At this time, I’ll create a function with a function name char_remove that accepts a string pointer and a character.

void char_remove(char * p, char search)

Inside this function, I’ll be creating a temporary pointer char *c. Then, start a while function until a null character in the string pointer is reached.

Following, is an if block that checks if the value of string pointer is equals to search. And if that true, let’s copy value of p to temporary pointer variable c and start a new while block and check if the value of temporary pointer variable reaches null character ‘\0’

While, this is true let’s replace current pointer by the following pointer and increase the pointer.

*c = *(c+1);

Just outside nested while loop decrease value of p, this is when we find and replace the character with following character we need to reset pointers.

After outside of the if block, let’s increase the pointer p.

Find the complete code below.

C Program to remove character from string using Pointer

#include<stdio.h>

void char_remove(char*, char);

int main()
{
	char word[150],ch;
	printf("Enter a string: ");
	gets(word);
	printf("Enter the character you want to remove: ");
	scanf("%c",&ch);
	
	char_remove(word,ch);
	
	printf("Output String: ");
	puts(word);
	
	return 0;
}

void char_remove(char * p, char search) {
	char *c;
	while( *p != '\0') {
		if(*p == search) {
			c = p;  
			while( *c != '\0') {				
				*c = *(c+1); 
				c++;								
			}
			p--;
		}
		p++;
	}
}

Find more C Programs on Author’s Github.