logo

テキスト内の単語を別の指定された単語で置換する C プログラム

3 つの文字列「str」、「oldW」、「newW」を指定します。タスクは、単語「oldW」の出現をすべて検索し、単語「newW」に置き換えることです。 例:

Input : str[] = 'xxforxx xx for xx' oldW[] = 'xx' newW[] = 'geeks' Output : geeksforgeeks geeks for geeks
推奨: で解決してください 練習する 解決策に進む前に、まず。

このアイデアは、元の文字列をたどって、文字列内に古い単語が出現する回数をカウントすることです。ここで、新しい単語を置換できるように、十分なサイズの新しい文字列を作成します。ここで、元の文字列を単語を置き換えて新しい文字列にコピーします。 

実装:



C
// C program to search and replace  // all occurrences of a word with  // other word.  #include   #include   #include   // Function to replace a string with another  // string  char* replaceWord(const char* s const char* oldW   const char* newW)  {   char* result;   int i cnt = 0;   int newWlen = strlen(newW);   int oldWlen = strlen(oldW);   // Counting the number of times old word   // occur in the string   for (i = 0; s[i] != ''; i++) {   if (strstr(&s[i] oldW) == &s[i]) {   cnt++;   // Jumping to index after the old word.   i += oldWlen - 1;   }   }   // Making new string of enough length   result = (char*)malloc(i + cnt * (newWlen - oldWlen) + 1);   i = 0;   while (*s) {   // compare the substring with the result   if (strstr(s oldW) == s) {   strcpy(&result[i] newW);   i += newWlen;   s += oldWlen;   }   else  result[i++] = *s++;   }   result[i] = '';   return result;  }  // Driver Program  int main()  {   char str[] = 'xxforxx xx for xx';   char c[] = 'xx';   char d[] = 'Geeks';   char* result = NULL;   // oldW string   printf('Old string: %sn' str);   result = replaceWord(str c d);   printf('New String: %sn' result);   free(result);   return 0;  }  
出力:
Old string: xxforxx xx for xx New String: GeeksforGeeks Geeks for Geeks

時間計算量 : の上)
補助スペース: O(n)

方法 2: このメソッドには、文字列のインプレース更新が含まれます。新しい文字を挿入するために余分なスペースのみを使用するため、より効率的です。 

実装:

C
// C Program to replace a word in a text by another given // word by inplace updation #include  #include  #include  void replaceWord(char* str char* oldWord char* newWord) {  char *pos temp[1000];  int index = 0;  int owlen;  owlen = strlen(oldWord);  // Repeat This loop until all occurrences are replaced.  while ((pos = strstr(str oldWord)) != NULL) {  // Bakup current line  strcpy(temp str);  // Index of current found word  index = pos - str;  // Terminate str after word found index  str[index] = '';  // Concatenate str with new word  strcat(str newWord);  // Concatenate str with remaining words after  // oldword found index.  strcat(str temp + index + owlen);  } } int main() {  char str[1000] oldWord[100] newWord[100];  printf('Enter the string: ');  gets(str);  printf('Enter the word to be replaced: ');  gets(oldWord);  printf('Replace with: ');  gets(newWord);  replaceWord(str oldWord newWord);  printf('nModified string: %s' str);  return 0; } 
入力:
1 xxforxx xx for xx xx geeks
出力:
geeksforgeeks geeks for geeks

時間計算量: O(n)
補助スペース: O(1)

クイズの作成