C 用2个字符串连接

C 用2个字符串连接,c,string,character,concatenation,C,String,Character,Concatenation,我见过使用“strcopy”和“strcat”实现这一点的方法,但我不允许使用任何预定义的字符串函数 我被给予: void str_cat_101(char const input1[], char const input2[], char result[]); 我必须把input1和input2中的字符放到结果中(从左到右)。我是否必须使用两个for循环,用变量I和j来表示参数列表中的两个不同字符串?我知道如何从一个字符串复制值,但我不知道如何从两个字符串传输值。谢谢你的帮助 下面是

我见过使用“strcopy”和“strcat”实现这一点的方法,但我不允许使用任何预定义的字符串函数

我被给予:

    void str_cat_101(char const input1[], char const input2[], char result[]);
我必须把input1和input2中的字符放到结果中(从左到右)。我是否必须使用两个for循环,用变量I和j来表示参数列表中的两个不同字符串?我知道如何从一个字符串复制值,但我不知道如何从两个字符串传输值。谢谢你的帮助

下面是我的string.c文件中的内容,但我觉得我做得不对

void str_cat_101(char const input1[], char const input2[], char result[])
{
   int i, j;
   for (i = 0; input1[i] != '\0'; i++)
   {
      result[i] = input1[i];
   }
   result[i] = '\0';
   for (j = 0; input2[j] != '\0'; j++)
   {
      result[j] = input2[j];
   }
   result[j] = '\0';
}
下面是我的测试用例:

void str_cat_101_tests(void)
{
   char input1[4] = {'k', 'a', 'r', '\0'};
   char input2[3] = {'e', 'n', '\0'};
   char result[7];

   str_cat_101(input1, input2, result);
   checkit_string("karen", result);
}

int main()
{
   str_cat_101_tests();

   return 0;
}
你可以这样做(阅读评论):

result[]
应足够大,即
strlen(input1)+strlen(input2)+1

编辑

只需更正第二个循环,就可以将其追加到
result[]
中,而不是从result中的零位置重新复制:

   for (j = 0; input2[j] != '\0'; j++, i++) // notice i++
   {
      result[i] = input2[j];   // notice `i` in index with result 
   } 
   result[i] = '\0';  // notice `i`

如果可以使用链表而不是数组作为输入字符串,那么只需将字符串1的最后一个字符的指针设置为字符串2的开头,就可以了。如果链表不是一个选项,那么您可以通过使用一个循环遍历两个字符串来使用额外的空间来存储这两个字符串。

您不明白“我不允许使用任何预定义的字符串函数”的哪一部分?抱歉,但我不能使用任何预定义的字符串函数,因此我认为我不能使用strcpy或strcat:(尽管如此,还是谢谢你。正如你上面所说,我改变了我的第二个for循环,但是测试仍然没有通过。)(我将把我的测试用例放在上面。@Karen。。它运行得很好,这是。。是的,我在终端窗口上写的东西中发现了一个拼写错误,谢谢!只需做两次同样的事情。开始复制第二个,在复制第一个的地方。展示你已经尝试过的,我们不会为你做作业。哦,对不起!我应该包括在内我做了什么。如果我想让你们做我的家庭作业,那我很抱歉。我很感激每个人都能就如何完成这个问题给出提示和想法,我永远不会使用这个网站来为我写家庭作业。我只是一个非常困惑的学生,对编程完全陌生。:)和我“我一定会编辑我的问题,包括我到目前为止所做的事情。不过谢谢你的帮助!
void str_cat_101(char const input1[], char const input2[], char result[])
{
   int i, j;
   for (i = 0; input1[i] != '\0'; i++)
   {
      result[i] = input1[i];
   }
//   result[i] = '\0';
   for (j = 0; input2[j] != '\0'; j++)
   {
      result[i+j] = input2[j];//Copy to the location of the continued
   }
   result[i+j] = '\0';
}
void str_cat_101(char const input1[], char const input2[], char result[])
{
   int i, j;
   for (i = 0; input1[i] != '\0'; i++)
   {
      result[i] = input1[i];
   }
//   result[i] = '\0';
   for (j = 0; input2[j] != '\0'; j++)
   {
      result[i+j] = input2[j];//Copy to the location of the continued
   }
   result[i+j] = '\0';
}