编写一个程序,输入两个字符串并将其连接起来,不要用strcat函数。用C语言代码编写
时间: 2023-06-07 21:07:18 浏览: 44
好的,以下是示例代码:
```
#include <stdio.h>
int main() {
char str1[100], str2[100], result[200];
int i = 0, j = 0;
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
// 拷贝第一个字符串到结果数组中
while (str1[i] != '\0') {
result[i] = str1[i];
i++;
}
// 拷贝第二个字符串到结果数组中
while (str2[j] != '\0') {
result[i] = str2[j];
i++;
j++;
}
// 结果数组末尾加上结束符
result[i] = '\0';
printf("连接后的字符串为:%s\n", result);
return 0;
}
```
以上代码中,我们使用了两个 while 循环将两个字符串拷贝到结果数组中,并且在末尾加上了结束符 '\0',最终输出结果即为连接后的字符串。
相关问题
编写一个程序,将两个字符串连接起来,不要用strcat函数。用C语言代码编写
好的,以下是用C语言代码编写一个将两个字符串连接起来的程序,不使用strcat函数:
```c
#include <stdio.h>
void my_strcat(char *str1, char *str2){
while(*str1){
str1++;
}
while(*str2){
*str1 = *str2;
str1++;
str2++;
}
*str1 = '\0';
}
int main()
{
char str1[50] = "Hello";
char str2[50] = " world!";
my_strcat(str1, str2);
printf("%s", str1);
return 0;
}
```
这个程序通过指针来实现字符串的连接。首先找到第一个字符串的结尾,然后遍历第二个字符串的每一个字符,并将其逐一拼接到第一个字符串的结尾,最后加上一个终止符。运行该程序将输出"Hello world!"。
使用C语言编写一个程序,将两个字符串连接起来,不要用strcat函数
好的,以下是使用C语言编写的将两个字符串连接起来的程序,不使用strcat函数:
```c
#include <stdio.h>
#include <string.h>
void my_strcat(char *s1, char *s2) {
while (*s1) {
s1++;
}
while (*s2) {
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0';
}
int main() {
char str1[50], str2[50];
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
my_strcat(str1, str2);
printf("连接后的字符串为:%s\n", str1);
return 0;
}
```
在这个程序中,我们定义了一个名为`my_strcat`的函数,它接受两个指向字符数组的指针作为参数,将第二个字符串连接到第一个字符串的末尾。具体实现如下:
- 使用一个while循环找到第一个字符串的末尾。
- 然后使用另一个while循环将第二个字符串的每个字符复制到第一个字符串的末尾。
- 最后将第一个字符串的末尾设置为'\0'。
在主函数中,我们首先从用户那里获取两个字符串,然后调用`my_strcat`函数将它们连接起来,最后输出结果。
需要注意的是,这个程序假设两个字符串都是以'\0'结尾的。如果不是,可能会导致程序崩溃或产生意外结果。所以,实际应用中还需要对输入进行有效性判断。