Write a C program to read any string from user and remove first occurrence of a given character from the string. The program should also use the concept of functions to remove the given character from string. How to remove first occurrences of a given character from the string.
Example :
Input string: I Love programming. I Love CodeForWin. I Love India.
Input character to remove: 'I'
Output: Love Programming. I Love CodeForWin. I Love India.
Happy coding ;)
Example :
Input string: I Love programming. I Love CodeForWin. I Love India.
Input character to remove: 'I'
Output: Love Programming. I Love CodeForWin. I Love India.
Required knowledge:
Basic C programming, If else, Loop, Array, String, FunctionsProgram:
/**
* C program to remove first occurrence of a character from the given string.
*/
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
/** Function declaration */
void removeFirst(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();
removeFirst(text, toRemove);
printf("\nOutput : %s", text);
return 0;
}
/**
* Function to remove first occurrence of a character from the string.
*/
void removeFirst(char * text, const char toRemove)
{
int i;
int len = strlen(text);
i=0;
/* Run loop until the first occurrence of the character is not found */
while(i<len && text[i]!=toRemove)
i++;
/*
* Shift all characters right to the position found above to one place left
*/
while(i<len-1)
{
text[i] = text[i+1];
i++;
}
/* Make the last character null */
text[i] = '\0';
}
Output
Enter any string: I Love programming. I Love CodeForWin. I Love India.
Enter character to remove from string: I
Output : Love programming. I Love CodeForWin. I Love India.
Enter character to remove from string: I
Output : Love programming. I Love CodeForWin. I Love India.
Happy coding ;)
You may also like
- String programming exercises and solutions.
- C program to find first occurrence of a given character in string.
- C program to remove last 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 find length of a String.
- C program to compare two strings.
- C program to copy two strings.
- C program to concatenate two strings.
- C program to count total number of alphabets, digits or special characters in the 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.