帮我用c语言写一个 创建键盘输入的三个字符串,然后把第一个和第二个字符串连接后保存到第三个字符串中并输出第三个字符串(不用strcpy函数)
时间: 2024-02-28 10:52:51 浏览: 24
好的,下面是代码实现:
```c
#include <stdio.h>
int main() {
char str1[50], str2[50], str3[100];
int i = 0, j = 0;
// 读取第一个字符串
printf("请输入第一个字符串:");
while ((str1[i++] = getchar()) != '\n');
// 读取第二个字符串
printf("请输入第二个字符串:");
while ((str2[j++] = getchar()) != '\n');
// 连接字符串
i = 0, j = 0;
while (str1[i] != '\0') {
str3[i] = str1[i];
i++;
}
while (str2[j] != '\0') {
str3[i++] = str2[j++];
}
str3[i] = '\0';
// 输出第三个字符串
printf("连接后的字符串为:%s\n", str3);
return 0;
}
```
这个程序会先读取用户输入的两个字符串,然后将它们连接起来并保存到一个新的字符串中。最后输出这个新的字符串。注意,这里没有使用 `strcpy` 函数,而是手动遍历字符数组实现字符串的连接。
相关问题
运用C语言定义一个二维数组,从键盘输入三个字符串,找出其中最大的并输出
好的,让我来回答这个编程问题。以下是代码示例:
```c
#include <stdio.h>
#include <string.h>
#define MAX_STR_LEN 100
#define STR_NUM 3
int main() {
char strings[STR_NUM][MAX_STR_LEN];
int max_len = 0;
int max_idx = -1;
// 从键盘输入三个字符串
for (int i = 0; i < STR_NUM; i++) {
printf("请输入第 %d 个字符串:", i+1);
scanf("%s", strings[i]);
int len = strlen(strings[i]);
if (len > max_len) { // 找出最长的字符串
max_len = len;
max_idx = i;
}
}
// 输出找到的最大字符串
printf("最大的字符串是:%s\n", strings[max_idx]);
return 0;
}
```
以上程序定义了一个二维字符数组 `strings`,用于存储从键盘输入的三个字符串。然后从数组中找出最长的字符串,并输出。
希望能对你有所帮助。
C语言查找从键盘上输入的三个字符串中最大的字符串
可以使用strcmp()函数实现字符串大小比较,可以使用循环来逐个比较输入的三个字符串,找出最大的字符串。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 50
int main() {
char str1[MAX_LEN], str2[MAX_LEN], str3[MAX_LEN];
printf("请输入三个字符串:\n");
scanf("%s %s %s", str1, str2, str3);
// 比较str1和str2
char max_str[MAX_LEN];
if (strcmp(str1, str2) > 0) {
strcpy(max_str, str1);
} else {
strcpy(max_str, str2);
}
// 再比较max_str和str3
if (strcmp(max_str, str3) < 0) {
strcpy(max_str, str3);
}
printf("最大的字符串是:%s\n", max_str);
return 0;
}
```
在这个示例代码中,我们定义了一个`MAX_LEN`常量来表示输入的字符串的最大长度,然后使用`scanf()`函数从键盘上读入三个字符串。接着,我们使用`strcmp()`函数来比较两个字符串的大小,如果第一个字符串比第二个字符串大,就把第一个字符串复制到`max_str`中,否则把第二个字符串复制到`max_str`中。最后,再用`strcmp()`函数比较`max_str`和第三个字符串的大小,如果第三个字符串比`max_str`大,就把第三个字符串复制到`max_str`中。最终,输出`max_str`即可。