将两个字符串连接起来,不要用strcat函数,请编写程序。
时间: 2023-04-24 22:05:19 浏览: 53
可以使用循环遍历第一个字符串,将其逐个字符复制到一个新的字符串中,然后再循环遍历第二个字符串,将其逐个字符复制到新的字符串的末尾即可。具体实现可以参考以下代码:
```c
#include <stdio.h>
int main() {
char str1[100], str2[100], new_str[200];
int i, j;
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
// 将第一个字符串复制到新的字符串中
for (i = 0; str1[i] != '\0'; i++) {
new_str[i] = str1[i];
}
// 将第二个字符串复制到新的字符串末尾
for (j = 0; str2[j] != '\0'; j++) {
new_str[i + j] = str2[j];
}
// 添加字符串结束符
new_str[i + j] = '\0';
printf("连接后的字符串为:%s\n", new_str);
return 0;
}
```
相关问题
编写程序,将两个字符串连接起来,不要使用strcat函数。
题目意思:请编写程序,将两个字符串连接起来,不要使用strcat函数。
解释:题目要求我们将两个字符串连接起来,但是不能使用strcat函数。strcat函数是C语言中的一个字符串操作函数,可以将一个字符串连接到另一个字符串的末尾。
那么我们可以使用循环和指针来实现字符串的连接。首先定义一个新的字符串数组result,然后循环将两个字符串的字符逐个复制到result数组中,直到两个字符串全部复制完毕。
具体实现代码如下:
```c
#include<stdio.h>
#include<string.h>
int main()
{
char s1[] = "hello";
char s2[] = "world";
char result[12];
int i = 0, j = 0;
while(s1[i] != '\0')
{
result[i] = s1[i];
i++;
}
while(s2[j] != '\0')
{
result[i+j] = s2[j];
j++;
}
result[i+j] = '\0';
printf("%s\n", result);
return 0;
}
```
运行结果:
```
helloworld
```
这个程序将s1和s2两个字符串连接到了一起,并输出了结果。
编写一个程序,将两个字符串连接起来,用strcat函数
好的,您可以使用以下代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char s1[100], s2[100];
printf("请输入第一个字符串:");
scanf("%s", s1);
printf("请输入第二个字符串:");
scanf("%s", s2);
strcat(s1, s2);
printf("连接后的字符串为:%s", s1);
return 0;
}
```
这个程序会要求您输入两个字符串,然后使用 `strcat` 函数将它们连接起来,并输出连接后的字符串。需要注意的是,为了避免缓冲区溢出,您需要确保两个字符串的总长度不超过数组的容量。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)