C语言7. 编一函数,连接2个字符串,输出连接后的字符串。
时间: 2024-02-10 08:10:46 浏览: 30
下面是一个用C语言实现的函数,可以连接两个字符串:
```c
#include <stdio.h>
#include <string.h>
void strconcat(char *s1, char *s2)
{
strcat(s1, s2);
}
int main()
{
char s1[100], s2[100];
printf("请输入第一个字符串:");
scanf("%s", s1);
printf("请输入第二个字符串:");
scanf("%s", s2);
strconcat(s1, s2);
printf("连接后的字符串是:%s\n", s1);
return 0;
}
```
该函数使用了一个库函数 strcat,可以将第二个字符串连接到第一个字符串的末尾。在主函数中,使用 scanf 函数从键盘上输入两个字符串,然后调用 strconcat 函数连接字符串,并输出结果。
相关问题
C语言编程 编一程序,将两个字符串连接起来,不要用strcat函数
好的,以下是C语言编程实现将两个字符串连接起来的代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char s1[100], s2[100];
int i, j, len1, len2;
// 输入字符串
printf("请输入第一个字符串:");
scanf("%s", s1);
printf("请输入第二个字符串:");
scanf("%s", s2);
// 计算字符串长度
len1 = strlen(s1);
len2 = strlen(s2);
// 将第二个字符串连接到第一个字符串的末尾
for(i = len1, j = 0; i < len1+len2; i++, j++) {
s1[i] = s2[j];
}
s1[i] = '\0'; // 添加字符串结束符
// 输出连接后的字符串
printf("连接后的字符串为:%s\n", s1);
return 0;
}
```
这段代码使用了一个for循环来完成将两个字符串连接起来的功能。在输入字符串后,我们使用strlen函数计算字符串长度,并将第二个字符串连接到第一个字符串的末尾。最后,我们添加字符串结束符,并输出连接后的字符串。
用c语言编一程序,将两个字符串连接起来,不要用strcat函数
以下是使用C语言将两个字符串连接起来的程序,不使用strcat函数:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
int len1, len2;
printf("Enter string 1: ");
gets(str1);
printf("Enter string 2: ");
gets(str2);
len1 = strlen(str1);
len2 = strlen(str2);
for(int i = 0; i < len2; i++) {
str1[len1 + i] = str2[i];
}
printf("Concatenated string: %s\n", str1);
return 0;
}
```
这个程序首先使用gets函数从标准输入中读取两个字符串,然后使用strlen函数计算出两个字符串的长度。接下来使用一个循环将第二个字符串中的每个字符拼接到第一个字符串的末尾。最后输出拼接后的字符串。
需要注意的是,由于使用gets函数存在安全隐患,因此在实际的开发中应该使用更为安全的函数,如fgets。