今天看Ellics Horowitz的<数据结构(C语言版)>中的子串的插入函数:
void strnins(char *s,char *t,int i)
{
char str[MAX_SIZE],*temp = str;
if (i<0||i>strlen(s))
{
fprintf(stderr,"Poisiton is out of bounds\n");
exit(1);
}
if (!strlen(s)) //s为空
{
strcpy(s,t);
}
else if (strlen(t))
{
strncpy(temp,s,i);
strcat(temp,t);
strcat(temp,(s+i));
strcpy(s,temp);
}
}
书中说该方法比较耗时间和空间,在实际中很少使用,可以改写该方法不使用temp变量。于是我对该算法进行了一点改进:
#include <stdio.h>
#include <string.h>
char * StrnInsert(char *dst,char *src,int i);
void main()
{
char str1[] = "0123456789";
char str2[] = "abcdef";
StrnInsert(str1,str2,5);
printf("%s\n",str1);
getchar();
}
char* StrnInsert(char *dst,char *src,int i)
{
if (i<0||i>strlen(dst))
{
fprintf(stderr,"Poisiton is out of bounds\n");
return NULL;
}
strcat(src,(dst+i));
strcpy((dst+i),src);
return dst;
}