[英]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.