Saturday 15 May 2010

string - Function to delete all occurrences of a word in a sentence in C -



string - Function to delete all occurrences of a word in a sentence in C -

i have code remove first occurrence of word sentence:

#include "stdio.h" #include "string.h" int delete(char *source, char *word); void main(void) { char sentence[500]; char word[30]; printf("please come in sentence. max 499 chars. \n"); fgets(sentence, 500, stdin); printf("please come in word deleted sentence. max 29 chars. \n"); scanf("%s", word); delete(sentence, word); printf("%s", sentence); } int delete(char *source, char *word) { char *p; char temp[500], temp2[500]; if(!(p = strstr(source, word))) { printf("word not found in sentence.\n"); homecoming 0; } strcpy(temp, source); temp[p - source] = '\0'; strcpy(temp2, p + strlen(word)); strcat(temp, temp2); strcpy(source, temp); homecoming 1; }

how modify delete occurrences of word in given sentence? can still utilize strstr function in case?

thanks help!

open different ways of doing too.

p.s. might sound homework question, it's past midterm question i'd resolve prepare midterm!

as side question, if utilize fgets(word, 30, stdin) instead of scanf("%s", word), no longer works , tells me word not found in sentence. why?

how modify to delete occurrences of word in given sentence?

there many ways, have suggested, , since open different ways of doing too... here different idea: sentence uses white space separate words. can utilize help solve problem. consider implementing these steps using fgets(), strtok() , strcat() break apart string, , reassemble without string remove.

0) create line buffer sufficient length read lines file (or pass in line buffer argument) 1) utilize while(fgets(...) new line file 2) create char *buf={0}; 3) create char *new_str; (calloc() memory new_str >= length of line buffer) 4) loop on buf = strtok();, using " \t\n" delimiter within loop: a. if (strcmp(buf, str_to_remove) != 0) //approve next token concatenation { strcat(new_str, buf); strcat(new_str, " ");}//if not str_to_remove, //concatenate token, , space 5) free allocated memory

new_str contains sentence without occurrences of str_to_remove.

here demo using set of steps (pretty much)

int delete(char *str, char *str_to_remove) { char *buf; char *new_str; new_str = calloc(strlen(str)+1, sizeof(char)); buf = strtok(str, " \t\n"); while(buf) { if(strcmp(buf, str_to_remove) != 0) { strcat(new_str, buf); strcat(new_str, " "); } buf = strtok(null, " \t\n"); } printf("%s\n", new_str); free(new_str); getchar(); homecoming 0; } int main(void) { delete("this sentence had withh bad withh word", "withh"); homecoming 0; }

c string

No comments:

Post a Comment