用c语言做一个代码,连接两个字符串(不用strcat函数)。输入形式:输入两行字符串。输出形式:连接两个字符串。
时间: 2024-05-11 19:15:11 浏览: 18
您好!可以通过以下程序实现连接两个字符串:
```
#include<stdio.h>
#include<string.h>
int main(){
char str1[100], str2[100], res[200];
int i, j, len1, len2;
printf("请输入第一个字符串:");
fgets(str1, sizeof(str1), stdin);
printf("请输入第二个字符串:");
fgets(str2, sizeof(str2), stdin);
len1 = strlen(str1);
len2 = strlen(str2);
for (i = 0; i < len1 - 1; i++) {
res[i] = str1[i];
}
for (j = 0; j < len2; j++) {
res[i + j] = str2[j];
}
res[i + j] = '\0';
printf("连接后的字符串为:%s", res);
return 0;
}
```
这个程序使用 fgets() 函数从标准输入获取两个字符串,然后使用循环将它们连接在一起,最后输出连接后的结果。希望这个程序对您有所帮助!
相关问题
用c语言写一个输入两个字符串并用char函数定义后将字符串连接的代码
下面是一个示例代码,可以让用户输入两个字符串,然后使用char函数将它们连接起来:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
strcat(str1, str2); // 使用 strcat 函数将两个字符串连接起来
printf("连接后的字符串为:%s\n", str1);
return 0;
}
```
在上述代码中,我们首先定义了两个字符数组 `str1` 和 `str2`,用于存储用户输入的两个字符串。然后,使用 `scanf` 函数分别读取用户输入的两个字符串。
接下来,我们使用 `strcat` 函数将两个字符串连接起来,并将结果保存在 `str1` 中。最后,通过 `printf` 函数将连接后的字符串输出到屏幕上。
用C语言程序写一个函数,将两个字符串连接,不用strcat函数
下面是一个示例函数,用于将两个字符串连接起来:
```c
#include <stdio.h>
void mystrcat(char *dest, const char *src) {
// 找到dest字符串的末尾
while (*dest != '\0') {
dest++;
}
// 将src字符串复制到dest字符串末尾
while (*src != '\0') {
*dest = *src;
dest++;
src++;
}
// 在最后添加字符串结束符
*dest = '\0';
}
int main() {
char dest[100] = "Hello, ";
char src[] = "world!";
mystrcat(dest, src);
printf("%s\n", dest); // 输出 "Hello, world!"
return 0;
}
```
该函数基本思路是先找到dest字符串的末尾,然后将src字符串复制到dest字符串的末尾,最后添加字符串结束符'\0'。需要注意的是,为了保证安全,我们将src参数声明为const char*,避免在函数内部修改其内容。