【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;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋说

感谢打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值