用一个函数实现输入的两个字符串的比较
时间: 2024-04-29 21:27:00 浏览: 10
可以使用标准库函数strcmp()实现字符串的比较,函数原型如下:
```C
int strcmp(const char *s1, const char *s2);
```
函数说明:
该函数比较字符串s1和s2,并返回下列值之一:
- 返回值为 0 则表示 s1 和 s2 相等。
- 返回值大于 0,则表示 s1 大于 s2。
- 返回值小于 0,则表示 s1 小于 s2。
示例代码:
```C
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20], str2[20];
printf("请输入两个字符串:\n");
scanf("%s%s", str1, str2);
int result = strcmp(str1, str2);
if(result == 0){
printf("字符串相等\n");
}else if(result > 0){
printf("第一个字符串大于第二个字符串\n");
}else{
printf("第一个字符串小于第二个字符串\n");
}
return 0;
}
```
相关问题
用一个函数实现两个字符串比较
可以使用strcmp()函数来比较两个字符串,该函数会返回一个整数值,其结果表示两个字符串的大小关系。
函数原型为:
```c
int strcmp(const char *str1, const char *str2);
```
其中,str1和str2分别是要比较的两个字符串,如果str1小于str2,返回一个负整数;如果str1等于str2,返回0;如果str1大于str2,返回一个正整数。
示例代码如下:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100], str2[100];
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
int res = strcmp(str1, str2);
if(res == 0)
printf("两个字符串相等\n");
else if(res < 0)
printf("%s 小于 %s\n", str1, str2);
else
printf("%s 大于 %s\n", str1, str2);
return 0;
}
```
用一个函数实现两个字符串的比较
可以使用 strcmp() 函数来比较两个字符串。该函数在 C 语言中非常常用,输入两个字符串,返回值为整型。如果两个字符串相同,返回值为 0。例如:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "hello";
char str2[50] = "world";
int result = strcmp(str1, str2);
if (result == 0) {
printf("The strings are equal.\n");
}
else if (result < 0) {
printf("The first string is less than the second.\n");
}
else {
printf("The first string is greater than the second.\n");
}
return 0;
}
```
输出结果:
```
The first string is less than the second.
```