如何将字符串的副本插入另一个字符串?

时间:2013-11-12 07:15:02

标签: c arrays string replace

所以,这是函数:

int strinsert(char *dst, int len, const char *src, int offset)

我需要将src字符串的副本从位置dst插入名为offset的字符串中。 参数len指定为数组dst保留的字符数。

代码的重要部分:

        int strinsert(char *dst, int len, const char *src, int offset)
{
strncpy(dst, src+offset, len);
char buf[100];
  strcpy(buf+len, src);
    len += strlen(src) ;
    strcpy(buf+len, dst+offset); 
    strcpy(dst, buf);

  return 1;
}

还是感觉有点不对......

编辑:在有人误解之前,我只是教自己如何用C语言编程,我发现了这个练习。顺便说一下,我没有真正找到一些很好的一维和二维阵列的学习资料,有人可以这么善良并发布一些吗?

1 个答案:

答案 0 :(得分:0)

您可以使用strncpy(),它是string.h库的函数。它会将num字符串的前source个字符复制到destination字符串。

char * strncpy(char * destination,const char * source,size_t num);

但在您的情况下,您需要第三个字符串,因为您无法扩展目标数组。您可以将目标数组的子字符串(从开始到偏移)复制到第三个数组中并连接其余数组。所以你需要做这样的事情:

char *dst = "ThisIsMyHomework";
char *src = "Not";
char finalString[50];
int offset = 6; //Assume we want to insert "Not" string between "ThisIs" and "MyHomework". So we want src array to start from 6th index of dst array.

strncpy(finalString, dst, offset); //finalString="ThisIs"
finalString[offset] = '\0'; //For finalString, you have to add "\0" manually because strcat will append other strings from 50. index of array if you don't
strcat(finalString, src); //finalString="ThisIsNot"
strcat(finalString, dst + offset); //finalString="ThisIsNotMyHomework"