PTA 6-2 替换子串* (10 分)

函数原型

// 替换子串
char* StrStuff(char *dst, int idx, int len, const char *src);

说明:dst 为指示目的串起始地址的指针,idx 为待删除子串的起始位置(下标),len 为待删除子串的长度,src 为指示待插入源串的起始地址的指针。函数将目的串 dst 中从下标 idx 处开始、长度为 len 的子串替换为源串 src,函数值为 dst

要求:函数能容错运行。若 len 不正确,则自动修正。若 idx 不正确,则不作任何处理。

裁判程序

#include <stdio.h>

// 替换子串
char* StrStuff(char *dst, int idx, int len, const char *src);

int main()
{
    char a[1024], b[1024];
    int i, n;
    gets(a);
    scanf("%d%d%*c", &i, &n);
    gets(b);
    StrStuff(a, i, n, b);
    puts(a);
    return 0;
}

/* 你提交的代码将被嵌在这里 */

输入样例1

abcd
1 2
efg

输出样例1

aefgd

输入样例2

abcd
1 5 (注:按3处理)
efgh

输出样例2

aefgh

输入样例3

abcd
2 -5 (注:按0处理)
efg

输出样例3

abefgcd

输入样例4

abcd
8 3
efg

输出样例4

abcd

实现代码:
 

char* StrInsert(char *dst, int index, const char *src){
	if(index>strlen(dst))
	 return dst;
	char str[65536];
	strcpy(str,dst+index);
    strcpy(dst + index,src);
	return strcat(dst,str);
}
char* StrStuff(char *dst, int idx, int len, const char *src){
	char str[1024];
	int slen=strlen(dst);
	if(idx>slen||idx<0)
     	return dst;
	if(len>slen-idx)
		len=slen-idx;
	if(len<=0)
		return StrInsert(dst,idx,src);	
	strcpy(dst+idx,dst+idx+len); 
	return StrInsert(dst,idx,src);
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值