【问题标题】:Concatenation with 2 strings与 2 个字符串连接
【发布时间】:2013-05-16 05:30:19
【问题描述】:

我已经看到使用“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;
}

【问题讨论】:

  • 做同样的事情两次。在复制完第一个的地方开始复制第二个。
  • 展示你的尝试,我们不会为你做功课。
  • 糟糕,对不起!我应该包括我所做的。抱歉,我好像想让你们做我的功课。我感谢所有发布关于如何解决问题的提示和想法的人,我永远不会使用这个网站来为我写作业。我只是一个对编程完全陌生的非常困惑的学生。 :) 我肯定会编辑我的问题以包括我到目前为止所做的事情。感谢您的帮助!

标签: c string character concatenation


【解决方案1】:
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';
}

【讨论】:

    【解决方案2】:

    如果您可以使用链表代替数组作为输入字符串,您只需将字符串 1 的最后一个字符的指针设置为字符串 2 的开头即可。如果链接列表不是一种选择,那么您可以使用额外的空间来存储两个字符串,方法是使用一个循环遍历它们。

    【讨论】:

      【解决方案3】:

      你可以这样做(阅读评论):

      void str_cat_101(char const input1[], char const input2[], char result[]){
        int i=0, j=0;
        while(input1[j]) // copy input1
          result[i++] = input1[j++];
        --i;
        j=0;
        while(input2[j]) // append intput2
          result[i++] = input2[j++];           
        result[i]='\0';
      }
      

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

      编辑

      只要纠正你的第二个循环,你将追加到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`
      

      【讨论】:

      • “我不允许使用任何预定义的字符串函数”的哪一部分你不明白?
      • 抱歉,我不能使用任何预定义的字符串函数,所以我认为我不能使用 strcpy 或 strcat。 :( 不过谢谢。
      • 所以我改变了我的第二个 for 循环,正如你上面所说的,但测试仍然没有通过。 :( 我会把我的测试用例放在上面。
      • @Karen .. 运行良好,这里是 link I tested online ..
      • 是的,我发现我在终端窗口上写的内容有错字,不过谢谢!
      猜你喜欢
      • 2014-05-14
      • 1970-01-01
      • 2015-01-13
      • 2011-02-03
      • 2020-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-09
      相关资源
      最近更新 更多