编写一个程序,将两个字符串连接起来,不要用strcat函数。
时间: 2023-04-24 11:07:32 浏览: 57
可以使用循环遍历两个字符串,将第一个字符串的每个字符依次存入一个新的字符串中,再将第二个字符串的每个字符依次存入新的字符串中,最后输出新的字符串即可。
示例代码:
```
#include <stdio.h>
int main() {
char str1[100], str2[100], newStr[200];
int i, j;
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
// 将第一个字符串存入新的字符串中
for (i = ; str1[i] != '\'; i++) {
newStr[i] = str1[i];
}
// 将第二个字符串存入新的字符串中
for (j = ; str2[j] != '\'; j++) {
newStr[i + j] = str2[j];
}
// 添加字符串结束符
newStr[i + j] = '\';
printf("连接后的字符串为:%s\n", newStr);
return ;
}
```
相关问题
编写一个程序,将两个字符串连接起来,用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` 函数将它们连接起来,并输出连接后的字符串。需要注意的是,为了避免缓冲区溢出,您需要确保两个字符串的总长度不超过数组的容量。
编写一个程序,将两个字符串连接起来,不要用strcat函数
可以使用循环遍历第一个字符串,将其逐个字符复制到一个新的字符串中,然后再遍历第二个字符串,将其逐个字符复制到新的字符串的末尾。具体实现可以参考以下代码:
```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 = ; str1[i] != '\'; i++) {
new_str[i] = str1[i];
}
// 复制第二个字符串到新字符串末尾
for (j = ; str2[j] != '\'; j++) {
new_str[i + j] = str2[j];
}
// 添加字符串结束符
new_str[i + j] = '\';
printf("连接后的字符串为:%s\n", new_str);
return ;
}
```
这个程序首先从用户那里获取两个字符串,然后使用两个循环将它们连接起来。第一个循环遍历第一个字符串,将其逐个字符复制到新字符串中。第二个循环遍历第二个字符串,将其逐个字符复制到新字符串的末尾。最后,程序在新字符串的末尾添加一个字符串结束符,然后输出连接后的字符串。