学习-编写函数将两个字符串连接起来的c语言函数
时间: 2023-12-06 07:44:31 浏览: 60
以下是将两个字符串连接起来的C语言函数的实现:
```c
#include <stdio.h>
#include <string.h>
void concat(char str1[], char str2[]) {
strcat(str1, str2);
printf("Concatenated string: %s", str1);
}
int main() {
char str1[100], str2[100];
printf("Enter string 1: ");
gets(str1);
printf("Enter string 2: ");
gets(str2);
concat(str1, str2);
return 0;
}
```
此函数使用`strcat()`函数将第二个字符串(`str2`)附加到第一个字符串(`str1`)的末尾。最后,使用`printf()`函数打印连接后的字符串(`str1`)。
请注意,`gets()`函数已被标记为不安全,因此不建议在实际程序中使用。您可以使用`fgets()`函数来代替。
相关问题
写一个函数,将两个字符串连接的c语言
下面是一个简单的函数,将两个字符串连接起来:
```c
#include <stdio.h>
#include <string.h>
void concat(char s1[], char s2[]) {
strcat(s1, s2);
}
int main() {
char str1[50] = "Hello ";
char str2[] = "World!";
concat(str1, str2);
printf("%s\n", str1); // Output: Hello World!
return 0;
}
```
该函数使用了 `strcat()` 函数,它可以将第二个字符串连接到第一个字符串的末尾。在主函数中,我们首先定义两个字符串,然后调用 `concat()` 函数将它们连接起来,并输出结果。
编写函数将两个字符串连接起来,要求在主函数里进行输入输出字符串。c语言
好的,以下是实现该功能的 C 语言代码示例:
```c
#include <stdio.h>
#include <string.h>
void concatString(char s1[], char s2[]) {
int len1 = strlen(s1), len2 = strlen(s2);
int i, j;
for (i = len1, j = 0; j < len2; i++, j++) {
s1[i] = s2[j];
}
s1[i] = '\0';
}
int main() {
char s1[100], s2[100];
printf("请输入第一个字符串:\n");
scanf("%s", s1);
printf("请输入第二个字符串:\n");
scanf("%s", s2);
concatString(s1, s2);
printf("连接后的字符串为:%s\n", s1);
return 0;
}
```
函数 `concatString` 接受两个字符数组作为参数,将第二个字符串连接到第一个字符串的末尾。在 `main` 函数中,我们获取用户输入的两个字符串,调用 `concatString` 函数进行连接,并输出连接后的结果。需要注意的是,我们在第一个字符串的末尾添加了一个空字符,以确保连接后的字符串是一个合法的 C 语言字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)