[英]Concatenating two char arrays in C
我有两个char数组(char string1 [7]和char string2 [256]),需要以特定格式打印。 这两个字符串都有以'\\ 0'空字节结尾的随机数量的条目。
我尝试通过将字符串复制到可以直接打印的新数组来实现此目的,但是它不起作用。
while(string2[i]!='\0')
{
if(i<9 && string1[i]!='\0')
{
Printline[i]=string1[i];
}
else if (i>9)
{
Printline[i]=string2[i];
}
i++;
}
printf("%s\n",Printline);
任何帮助深表感谢 :)
int main(void) {
char string1[7];
char string2[256];
strncpy(string1, "str1", 6);
strcpy(string2, "This is string 2.");
printf("%-8s %s", string1, string2);
return 0;
}
编译并运行后,上面的代码将输出:
str1这是字符串2。
%-8s
格式规范指出,如果给定的字符串长度少于8个字符(不包括'\\0'
),则该字符串后将带有空格(空格),以占用8个房间。
此外,第9个字符将是一个空格,其余的将由string2
填充。
to . 编辑: strncpy
函数用于string1
以确保将不超过6个字符从复制到 。 请记住,第7个字符将是一个空终止符( '\\0'
)。
我认为需要更正/澄清以下内容,而不要发布代码,以便您有机会学习并尝试对其进行修复。
while(string2[i]!='\0') /* and further checks in the code, it appears that
the string2 has larger set of characters and
exceeds a count of 9 */
{
if (i<9 && string1[i]!='\0') /* What happens when (i < 9)
but string1[i] has already
reached the '\0'? */
{
Printline[i]=string1[i];
}
else if (i>9)
{
Printline[i]=string2[i];
}
/* What about (i == 9)? */
i++;
}
/* Not including '\0' from string2 before printing Printline
would eventually crash the program */
printf("%s\n",Printline);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.