strcmp怎么比较
时间: 2024-04-23 14:18:11 浏览: 16
strcmp是C语言中用于比较两个字符串的函数。它的原型为:
```c
int strcmp(const char *str1, const char *str2);
```
该函数会比较两个字符串str1和str2,并返回一个整数值,表示它们的大小关系。具体的比较规则如下:
- 如果str1和str2相等,返回值为0;
- 如果str1大于str2,返回值大于0;
- 如果str1小于str2,返回值小于0。
strcmp函数会逐个比较两个字符串中对应位置的字符,直到遇到不相等的字符或者其中一个字符串结束为止。比较时使用的是字符的ASCII码值。
下面是一个使用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",因为在ASCII码中,字符'h'的值小于字符'w'的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![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_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)