由键盘任意输入2串字符,将它们连接为一串 宇符(不允许使用strcat函数)。
时间: 2024-03-18 22:42:12 浏览: 13
您可以使用循环遍历的方法将两个字符串连接起来,具体实现可以参考以下代码:
```c
#include <stdio.h>
int main() {
char str1[100], str2[100], result[200];
int i, j;
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
// 将第一个字符串复制到结果字符串中
for (i = 0; str1[i] != '\0'; i++) {
result[i] = str1[i];
}
// 将第二个字符串复制到结果字符串中
for (j = 0; str2[j] != '\0'; j++) {
result[i + j] = str2[j];
}
// 将结果字符串末尾加上结束符
result[i + j] = '\0';
printf("连接后的字符串为:%s", result);
return 0;
}
```
这段代码会先让用户输入两个字符串,然后使用两个循环分别将两个字符串中的字符逐个复制到结果字符串中,最后在结果字符串末尾加上结束符。
相关问题
由键盘任意输入2串字符,将它们连接为一串字符(不允许使用strcat函数)。
可以使用字符串拼接的方式将两个字符串连接起来。具体步骤如下:
1. 定义一个新的字符串,长度为两个字符串长度之和加1(加1是为了留出字符串结尾的'\0')。
2. 使用循环将第一个字符串的每个字符依次复制到新字符串中。
3. 再使用循环将第二个字符串的每个字符依次复制到新字符串中。
4. 在新字符串的最后一个位置加上'\0',表示字符串的结尾。
5. 最后输出新字符串即可。
示例代码如下:
```
#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];
}
// 在新字符串的最后一个位置加上'\0'
new_str[i + j] = '\0';
printf("连接后的字符串为:%s\n", new_str);
return 0;
}
```
C语言由键盘任意输入2串字符,将它们连接为一串字符(不允许使用strcat函数)。
可以使用一个循环将第一串字符逐一存入第三个字符串中,再用另一个循环将第二串字符接在第三个字符串的末尾。具体实现可以参考以下代码:
#include <stdio.h>
int main() {
char str1[100], str2[100], str3[200];
int i, j;
printf("请输入第1串字符:");
scanf("%s", str1);
printf("请输入第2串字符:");
scanf("%s", str2);
for (i = 0; str1[i] != '\0'; i++) {
str3[i] = str1[i];
}
for (j = 0; str2[j] != '\0'; j++) {
str3[i+j] = str2[j];
}
str3[i+j] = '\0';
printf("连接后的字符串为:%s\n", str3);
return 0;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)