编写一个函数fun实现字符串连接功能(不使用strcat函数)。 主函数输入两个字符串,调用函数,输出连接后的字符串
时间: 2023-04-23 11:06:28 浏览: 172
以下是一个实现字符串连接功能的函数fun的示例代码:
```c
#include <stdio.h>
void fun(char *str1, char *str2, char *result) {
int i = 0, j = 0;
while (str1[i] != '\0') {
result[i] = str1[i];
i++;
}
while (str2[j] != '\0') {
result[i+j] = str2[j];
j++;
}
result[i+j] = '\0';
}
int main() {
char str1[100], str2[100], result[200];
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
fun(str1, str2, result);
printf("连接后的字符串为:%s\n", result);
return 0;
}
```
该函数接受两个字符串和一个结果字符串作为参数,将两个字符串连接起来存储到结果字符串中。函数内部使用两个while循环分别将两个字符串的字符逐个复制到结果字符串中,直到遇到字符串结束符'\0'为止。最后在结果字符串的末尾添加一个'\0',表示字符串的结束。
在主函数中,先输入两个字符串,然后调用fun函数进行字符串连接,最后输出连接后的字符串。