Write a C program to input any string from user and remove first occurrence of a given word from string. Write a function to remove first occurrence of a word from the string. How to remove first occurrence of a word from the string in C programming.
Example:
Input string : I love to code.
Input word to remove : to
Output : I love code.
Before continuing to this program you must know how to find the first occurrence of a word in the given string.
Happy coding ;)
Example:
Input string : I love to code.
Input word to remove : to
Output : I love code.
Required knowledge:
Basic C programming, If else, Loop, Array, StringBefore continuing to this program you must know how to find the first occurrence of a word in the given string.
Program:
/**
* C program to remove the first occurrence of a word in a string
*/
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
/** Function declaration */
void removeFirst(char * text, const char * toRemove);
int main()
{
char text[MAX_SIZE];
char toRemove[MAX_SIZE];
/*
* Reads a string from user and character to be searched
*/
printf("Enter any string: ");
gets(text);
printf("Enter string to be removed: ");
gets(toRemove);
removeFirst(text, toRemove);
printf("\nFinal string after removing '%s' = %s", toRemove, text);
return 0;
}
/**
* Removes the first occurrence of a string in another string
*/
void removeFirst(char * text, const char * toRemove)
{
int i, j;
int len, removeLen;
int found = 0;
len = strlen(text);
removeLen = strlen(toRemove);
for(i=0; i<len; i++)
{
found = 1;
for(j=0; j<removeLen; j++)
{
if(text[i+j] != toRemove[j])
{
found = 0;
break;
}
}
/*
* If word has been found then remove it by shifting characters right to it to left.
*/
if(found == 1)
{
for(j=i; j<len-removeLen; j++)
{
text[j] = text[j + removeLen];
}
text[j] = '\0';
break;
}
}
}
Output
Enter any string: I write code.
Enter string to be removed: write
Final string after removing 'write' = I code.
Enter string to be removed: write
Final string after removing 'write' = I code.
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 first occurrence of a character from the 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 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.