编写一个函数,将两个字符串连接。只能用c语言
时间: 2023-06-24 07:03:06 浏览: 59
可以使用C语言中的字符串拼接函数`strcat()`来实现两个字符串的连接。
示例代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "Hello, ";
char str2[] = "world!";
strcat(str1, str2); // 将str2连接到str1后面
printf("连接后的字符串为:%s\n", str1);
return 0;
}
```
输出结果为:
```
连接后的字符串为:Hello, world!
```
可以看到,通过`strcat()`函数,我们把`str2`字符串连接到了`str1`字符串的末尾。注意,`strcat()`函数会改变原来的字符串,因此在使用时需要注意字符串的长度,以避免发生内存溢出等错误。
相关问题
用c语言编写一个函数,实现将两个字符串连接
以下是一个用 C 语言编写的字符串连接函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* concat(char* str1, char* str2) {
int len1 = strlen(str1);
int len2 = strlen(str2);
char* result = (char*) malloc(len1 + len2 + 1);
if (result == NULL) {
printf("Error: memory allocation failed.\n");
exit(1);
}
strcpy(result, str1);
strcat(result, str2);
return result;
}
int main() {
char str1[] = "hello, ";
char str2[] = "world!";
char* result = concat(str1, str2);
printf("%s\n", result);
free(result);
return 0;
}
```
这个函数接受两个字符串作为参数,先计算出这两个字符串的长度,然后根据长度动态分配内存空间,将两个字符串拼接在一起后返回结果。在主函数中调用该函数,并打印输出结果后需要释放内存空间。
用C语言程序写一个函数,将两个字符串连接
以下是一个用C语言编写的字符串连接函数:
```c
#include <stdio.h>
#include <string.h>
void string_concat(char s1[], char s2[]) {
strcat(s1, s2);
}
int main() {
char str1[100] = "Hello, ";
char str2[] = "world!";
string_concat(str1, str2);
printf("%s\n", str1);
return 0;
}
```
该函数使用了C标准库中的`strcat`函数,将`s2`字符串连接到`s1`字符串的末尾。注意,在调用该函数之前,需要确保`s1`数组足够大,能够容纳下连接后的新字符串。