函数原型
// 替换子串 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); }