输入俩个字符串,输出其中较大的一个字符串,.使用 strcmp 函数
时间: 2024-02-18 18:05:56 浏览: 42
好的,您可以使用 `strcmp()` 函数实现这个功能。`strcmp()` 函数是 C 语言中的一个字符串比较函数,可以用来比较两个字符串的大小。
下面是使用 `strcmp()` 函数的代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
int result;
printf("请输入第一个字符串:");
gets(str1);
printf("请输入第二个字符串:");
gets(str2);
result = strcmp(str1, str2);
if (result >= 0) {
printf("%s 比 %s 大\n", str1, str2);
} else {
printf("%s 比 %s 大\n", str2, str1);
}
return 0;
}
```
在这个程序中,我们使用 `gets()` 函数从用户输入中获取两个字符串,并使用 `strcmp()` 函数比较它们的大小。如果 `result` 大于等于 0,则表示第一个字符串比第二个字符串大,反之则表示第二个字符串比第一个字符串大。最后,我们根据比较结果输出较大的那个字符串。
注意:`gets()` 函数存在安全问题,不建议在实际代码中使用,可以使用 `fgets()` 函数代替。
相关问题
从键盘输入3个字符串,按由小到大排序(使用strcmp函数
好的,可以使用以下代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], str3[100];
printf("请输入三个字符串:\n");
scanf("%s %s %s", str1, str2, str3);
// 使用strcmp比较字符串大小,进行排序
if (strcmp(str1, str2) > 0) {
char temp[100];
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
}
if (strcmp(str1, str3) > 0) {
char temp[100];
strcpy(temp, str1);
strcpy(str1, str3);
strcpy(str3, temp);
}
if (strcmp(str2, str3) > 0) {
char temp[100];
strcpy(temp, str2);
strcpy(str2, str3);
strcpy(str3, temp);
}
printf("排序后的字符串为:\n");
printf("%s\n%s\n%s\n", str1, str2, str3);
return 0;
}
```
输入三个字符串后,程序会使用strcmp函数进行比较,然后按照从小到大的顺序进行排序输出。
使用strcmp函数比较两个字符串
strcmp函数是C语言中的一个字符串比较函数,可以用来比较两个字符串是否相等。其函数原型为:
```c
int strcmp(const char* str1, const char* str2);
```
其中,str1和str2分别是要比较的两个字符串,函数返回值为整型,表示比较结果:
- 如果str1和str2相等,则返回0;
- 如果str1小于str2,则返回一个负数;
- 如果str1大于str2,则返回一个正数。
在比较时,函数会从两个字符串的第一个字符开始逐一比较,直到出现不同字符或者其中一个字符串结束为止。如果两个字符串的长度不同,那么在比较时会先比较短的那个字符串的所有字符,如果都相等,则返回两个字符串长度的差值。
例如,下面的代码演示了如何使用strcmp函数比较两个字符串:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if (result == 0) {
printf("str1和str2相等\n");
} else if (result < 0) {
printf("str1小于str2\n");
} else {
printf("str1大于str2\n");
}
return 0;
}
```
输出结果为:str1小于str2
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)