我已经看过使用“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;
}
答案 0 :(得分:0)
你可以这样做(阅读评论):
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`
答案 1 :(得分:0)
如果您可以使用链接列表而不是数组作为输入字符串,您所要做的就是将字符串1的最后一个字符的指针设置为字符串2的头部,您就完成了。如果链接列表不是一个选项,那么您可以使用额外的空间来存储两个字符串,方法是使用一个循环遍历它们。
答案 2 :(得分: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';
}