deleting a word with copy fuction c code
Here is an example of C code that deletes a word using the strcpy
function:
#include <stdio.h>
#include <string.h>
void deleteWord(char str, const char word) {
char* found = strstr(str, word);
if (found != NULL) {
size_t wordLen = strlen(word);
memmove(found, found + wordLen, strlen(found + wordLen) + 1);
}
}
int main() {
char str[100] = "Hello world! This is a test.";
const char* word = "world";
deleteWord(str, word);
printf("%s\n", str);
return 0;
}
Explanation:
The code includes the necessary header files
stdio.h
andstring.h
which provide the functions and definitions used in the code.The function
deleteWord
is defined with two parameters:str
which is the string from which the word will be deleted, andword
which is the word to be deleted.Inside the
deleteWord
function, thestrstr
function is used to find the first occurrence of theword
in thestr
. The function returns a pointer to the first occurrence of theword
instr
, orNULL
if theword
is not found.If the
word
is found (found
is notNULL
), thestrlen
function is used to determine the length of theword
.The
memmove
function is then used to move the remaining characters after theword
in thestr
to overwrite theword
. Thememmove
function is used instead ofstrcpy
because it handles overlapping memory regions correctly.Finally, the
main
function is defined. It declares a character arraystr
with a size of 100 and initializes it with the string "Hello world! This is a test." It also declares a constant character pointerword
which points to the word "world".The
deleteWord
function is called with thestr
andword
as arguments to delete the word "world" from thestr
.The modified
str
is then printed using theprintf
function.The program returns 0 to indicate successful execution.
I hope this code and explanation help you understand how to delete a word using the strcpy
function in C. Let me know if you have any further questions.