在这个程序中,我们给定了三个字符串 txt、oldword 和 newword。我们的任务是创建一个 C 程序,将文本中的一个单词替换为另一个给定的单词。
该程序将搜索文本中所有出现的 oldword,并将其替换为 newword。
让我们举个例子来理解这个问题 –
输入
text = “I am learning programming”oldword = “learning”newword = “practicing”
登录后复制
输出
“I am practicing programming”
登录后复制
为了解决这个问题,我们首先会找到字符串中旧单词出现的次数,然后创建一个新的字符串,将文本中的单词替换掉。
C程序:用另一个给定的单词替换文本中的一个单词
// C程序:用另一个给定的单词替换文本中的一个单词
示例
在线演示
#include #include #include 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] != ''; 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", newString);}int main() { char str[] = "I am learning programming"; char c[] = "learning"; char d[] = "practicing"; char *result = NULL; printf("Original string: %s
", str); replaceWordInText(str, c, d); return 0;}
登录后复制
输出
Original string: I am learning programmingNew String: I am practicing programming
登录后复制
以上就是C程序:将文本中的一个单词替换为另一个给定的单词的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2582843.html