用一个函数实现两个字符串的比较
时间: 2024-05-11 16:18:48 浏览: 23
可以使用字符串比较函数strcmp()来比较两个字符串。该函数在C语言的头文件<string.h>中定义。
函数原型:
```
int strcmp(const char *str1, const char *str2);
```
参数说明:
- str1:要比较的第一个字符串。
- str2:要比较的第二个字符串。
返回值:
- 如果str1小于str2,则返回一个负整数。
- 如果str1等于str2,则返回0。
- 如果str1大于str2,则返回一个正整数。
示例代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "hello";
char str2[20] = "world";
int result = strcmp(str1, str2);
if (result < 0) {
printf("%s is less than %s\n", str1, str2);
} else if (result == 0) {
printf("%s is equal to %s\n", str1, str2);
} else {
printf("%s is greater than %s\n", str1, str2);
}
return 0;
}
```
输出结果:
```
hello is less than world
```
相关问题
用一个函数实现两个字符串比较
可以使用strcmp函数来实现两个字符串的比较。该函数会比较两个字符串的每一个字符,直到遇到字符串结束符'\0'或者两个字符不相等为止。
函数原型如下:
```c
int strcmp ( const char * str1, const char * str2 );
```
其中,str1和str2是要比较的两个字符串,返回值为0表示两个字符串相等,小于0表示str1小于str2,大于0表示str1大于str2。
示例代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
char str3[] = "hello";
int result1 = strcmp(str1, str2);
int result2 = strcmp(str1, str3);
printf("result1: %d\n", result1); //-15
printf("result2: %d\n", result2); //0
return 0;
}
```
在上面的示例中,我们使用strcmp函数比较了str1和str2、str1和str3两个字符串,结果分别为-15和0。
一个函数实现两个字符串的比较
可以使用字符串库中的strcmp函数来比较两个字符串。该函数会返回一个整数值,如果两个字符串相等则返回0,如果第一个字符串小于第二个字符串则返回一个负数,如果第一个字符串大于第二个字符串则返回一个正数。
示例代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if(result == 0) {
printf("两个字符串相等\n");
} else if(result < 0) {
printf("第一个字符串小于第二个字符串\n");
} else {
printf("第一个字符串大于第二个字符串\n");
}
return 0;
}
```
输出结果为:
```
第一个字符串小于第二个字符串
```
相关推荐
![](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)
![](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)