本文目錄一覽:
C語言:將兩個字元串連接起來。
#include stdio.h
int main()
{
char s1[80],s2[40];
int i=0,j=0;
printf(“\nInput the first string:”);
scanf(“%s”,s1);
printf(“\nInput the second string:”);
scanf(“%s”,s2);
while (s1[i] !=’\0′)
i++;
while (s2[j] !=’\0′)
s1[i++]=s2[j++]; /* 拼接字元到s1 */
s1[i] =’\0′;
printf(“\nNew string: %s”,s1);
}
用C語言怎麼將兩個字元串連接起來?
這些是宏的功能。
#是將一個參數轉換為字元串。##可以連接字元串
比如這樣:
#include stdio.h
#define STR(a,b) a##b
int main()
{
printf(“%s\n”,STR(“123″,”456”));
return 0;
}
C語言中怎麼樣將兩個字元串連接起來
1)簡單來,直接用 strcat 函數,需要包含頭文件 string.h2)自己實現的話也不麻煩,但是要考慮一些細節:假設兩個字元串指針為 str1,str2 ,現在要講 str1 和 str2 連接成一個新的字元串。a.考慮指針 str1,str2 是否非空b.如果將str2的內容直接連接到str1的末尾,要考慮str1是否有足夠的剩餘空間來放置連接上的str2的內容。如果用一個新的內存空間來保存str1和str2的連接結果,需要動態分配內存空間。
用C語言:寫一個函數,將兩個字元串連接
字元串連接:即將字元串b複製到另一個字元a的末尾,並且字元串a需要有足夠的空間容納字元串a和字元串b。
#includestdio.h
void mystrcat(char a[],char b[]){//把a和b拼接起來
int i=0,j=0;
while(a[i++]!=’\0′);
i–;
while(b[j]!=’\0′){
a[i++]=b[j++];
}
a[i]=’\0′;
}
int main()
{
char a[100],b[100];
gets(a);
gets(b);
mystrcat(a,b);
puts(a);
return 0;
}
/*
運行結果:
abc
def
abcdef
*/
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/183109.html