用c语言将两个字符串连接
时间: 2023-04-09 13:05:02 浏览: 122
可以使用 strcat 函数将两个字符串连接起来,示例代码如下:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello, ";
char str2[50] = "world!";
strcat(str1, str2);
printf("%s", str1);
return 0;
}
```
输出结果为:Hello, world!
相关问题
c语言将两个字符串连接起来的函数
C语言中将两个字符串连接起来的函数是strcat(),函数原型如下:
```c
char *strcat(char *dest, const char *src);
```
其中,dest是目标字符串,src是源字符串,函数会将源字符串拼接到目标字符串的末尾,并返回目标字符串的指针。
需要注意的是,目标字符串必须足够大,能够容纳新加入的源字符串,否则可能会导致缓冲区溢出的问题。
以下是一个使用strcat()函数将两个字符串连接起来的例子:
```c
#include <stdio.h>
#include <string.h>
int main() {
char dest[20] = "Hello";
char src[] = "World";
strcat(dest, src);
printf("%s\n", dest);
return 0;
}
```
输出结果为:
```
HelloWorld
```
用c语言将两个字符串连接,不要用stract函数。
可以用循环来实现字符串连接,具体步骤如下:
1.先找到第一个字符串的结尾位置。
2.从第一个字符串的结尾位置开始,依次将第二个字符串中的字符赋值给第一个字符串对应的位置。
3.在第一个字符串的结尾位置添加字符串结束符号'\0'。
下面是示例代码:
```c
#include <stdio.h>
int main() {
char str1[100] = "hello";
char str2[50] = ", world!";
int i, j;
// 找到 str1 的结尾位置
i = 0;
while (str1[i] != '\0') {
i++;
}
// 将 str2 中的字符依次赋值给 str1
j = 0;
while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
// 添加字符串结束符号
str1[i] = '\0';
printf("Result: %s\n", str1);
return 0;
}
```
输出结果为:Result: hello, world!