c语言使用函数将两个字符串连接
时间: 2023-09-28 13:05:52 浏览: 59
可以使用C语言中的字符串库函数strcat()来将两个字符串连接起来。下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[] = "World!";
strcat(str1, str2);
printf("Concatenated string: %s", str1);
return 0;
}
```
输出结果为:
```
Concatenated string: HelloWorld!
```
在这个示例中,我们首先声明了一个字符串数组str1,它的长度为50,同时初始化为"Hello"。然后我们声明了另一个字符串数组str2,它的长度没有指定,但是被初始化为"World!"。
我们调用了strcat()函数,它将str2中的内容追加到了str1的末尾,因此最终输出的结果是"HelloWorld!"。需要注意的是,strcat()函数会修改第一个参数指向的字符串,因此我们需要保证第一个参数的长度足够大,可以容纳下两个字符串的内容。
相关问题
C语言用函数连接两个字符串
可以使用以下函数来连接两个字符串:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *concat(char *s1, char *s2) {
char *result = malloc(strlen(s1) + strlen(s2) + 1);
if (result == NULL) {
printf("Error: Unable to allocate memory for result string.\n");
exit(1);
}
strcpy(result, s1);
strcat(result, s2);
return result;
}
int main() {
char s1[] = "Hello, ";
char s2[] = "world!";
char *result = concat(s1, s2);
printf("Result: %s\n", result);
free(result);
return 0;
}
```
在这个函数中,我们首先使用`malloc`函数动态地分配内存来存储连接后的字符串。然后,我们使用`strcpy`函数将第一个字符串复制到结果字符串中,使用`strcat`函数将第二个字符串连接到结果字符串中。最后,我们将结果字符串返回给调用者。
在主函数中,我们调用`concat`函数来连接两个字符串,并将结果保存在一个指针中。最后,我们输出结果,并使用`free`函数释放结果字符串的内存。
需要注意的是,在使用动态分配的内存时,需要在使用完毕后使用`free`函数将其释放,以免造成内存泄漏。
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
```