采用数组的方法,实现字符串的拼接
采用C语言实现字符串的拼接,终端输入一个字符串arr,终端再输入一个字符串brr,拼接为一个字符串。
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
char arr[20]={0};
char brr[20]={0};
char crr[50]={0};//注意加'\0',保证不会出现乱码
int i,j;
int count=0;
printf( " 请输入要拼接的字符串\n");
gets(arr);
printf( " 请输入要拼接的字符串\n");
gets(brr);
for(i=0;arr[i] != '\0';i++)
{
crr[i]=arr[i];
count++;
}
for(j=0;brr[j] !='\0';j++)
{
crr[count+j]=brr[j];
}
puts(crr);
return 0;
}
运行结果:
请输入要拼接的字符串
hello
请输入要拼接的字符串
world
hello world
字符串拼接函数:strcat
在C语言中,可以使用字符串拼接函数strcat()
来将两个字符串连接在一起。
以下是一个例子显示了如何使用strcat()
函数:
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[50] = " World!";
strcat(str1, str2);
printf("%s\n", str1);
return 0;
}
输出结果为:
Hello World!
在上面的例子中,我们使用了strcat()
函数将两个字符串str1
和str2
连接在一起,结果存储在str1
中。注意,str1
的大小要足够大以容纳两个连接后的字符串。