【PTA数据结构 | C语言版】字符串替换算法
本专栏持续输出数据结构题目集,欢迎订阅。
文章目录
- 题目
- 代码
题目
请编写程序,将给定主串 s 中的子串 sub_s 替换成另一个给定字符串 t,再输出替换后的主串 s。
输入格式:
输入给出 3 个非空字符串,依次为:主串 s、主串中待替换的子串 sub_s、将要替换掉 sub_s 的字符串 t。每个字符串占一行,长度不超过 1000 个字符,以回车结束(回车不算在字符串内)。
题目保证替换后的主串长度仍然不超过 1000 个字符。
输出格式:
在一行中输出替换后的主串 s。
输入样例 1:
This is a simple test.
is
at
输出样例 1:
That at a simple test.
输入样例 2:
This is a test.
simple
what
输出样例 2:
This is a test.
代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>int replace_sub_str(const char *str, const char *substr, const char *repstr, char *result) {const char *p = str;char *t = result;int count = 0;size_t sub_len = strlen(substr);size_t rep_len = strlen(repstr);while (*p) {if (strncmp(p, substr, sub_len) == 0) {count++;memcpy(t, repstr, rep_len);t += rep_len;p += sub_len;} else {*t++ = *p++;}}*t = '\0';return count;
}int main() {char s[10001] = {0};char sub_s[10001] = {0};char t[10001] = {0};// 读取输入字符串fgets(s, sizeof(s), stdin);s[strcspn(s, "\n")] = 0; // 移除换行符fgets(sub_s, sizeof(sub_s), stdin);sub_s[strcspn(sub_s, "\n")] = 0;fgets(t, sizeof(t), stdin);t[strcspn(t, "\n")] = 0;char result[1001] = {0};int num = replace_sub_str(s, sub_s, t, result);printf("%s\n", result);return 0;
}