Home > Backend Development > C++ > C program: Replace a word in text with another given word

C program: Replace a word in text with another given word

WBOY
Release: 2023-09-08 22:37:02
forward
1407 people have browsed it

C program: Replace a word in text with another given word

在这个程序中,我们给定了三个字符串 txt、oldword 和 newword。我们的任务是创建一个 C 程序,将文本中的一个单词替换为另一个给定的单词。

该程序将搜索文本中所有出现的 oldword,并将其替换为 newword

让我们举个例子来理解这个问题 -

输入

text = “I am learning programming”
oldword = “learning”
newword = “practicing”
Copy after login

输出

“I am practicing programming”
Copy after login

为了解决这个问题,我们首先会找到字符串中旧单词出现的次数,然后创建一个新的字符串,将文本中的单词替换掉。

C程序:用另一个给定的单词替换文本中的一个单词

// C程序:用另一个给定的单词替换文本中的一个单词

示例

 在线演示

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void replaceWordInText(const char *text, const char *oldWord, const char *newWord) {
   int i = 0, cnt = 0;
   int len1 = strlen(newWord);
   int len2 = strlen(oldWord);
   for (i = 0; text[i] != &#39;\0&#39;; i++) {
      if (strstr(&text[i], oldWord) == &text[i]) {
         cnt++;
         i += len2 - 1;
      }
   }
   char *newString = (char *)malloc(i + cnt * (len1 - len2) + 1);
   i = 0;
   while (*text) {
      if (strstr(text, oldWord) == text) {
         strcpy(&newString[i], newWord);
         i += len1;
         text += len2;
      }
      else
      newString[i++] = *text++;
   }
   printf("New String: %s</p><p>", newString);
}
int main() {
   char str[] = "I am learning programming";
   char c[] = "learning";
   char d[] = "practicing";
   char *result = NULL;
   printf("Original string: %s</p><p>", str);
   replaceWordInText(str, c, d);
   return 0;
}
Copy after login

输出

Original string: I am learning programming
New String: I am practicing programming
Copy after login

The above is the detailed content of C program: Replace a word in text with another given word. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template