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

C program to remove first occurrence of a word from string

$
0
0
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.

Required knowledge:

Basic C programming, If else, Loop, Array, String

Before 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
X
_
Enter any string: I write code.
Enter string to be removed: write

Final string after removing 'write' = I  code.

Happy coding ;)



Viewing all articles
Browse latest Browse all 132

Trending Articles