strcmp
时间: 2023-08-28 16:17:56 浏览: 64
`strcmp`是C语言中用于比较两个字符串的函数,函数原型为:
```c
int strcmp(const char *s1, const char *s2);
```
该函数将比较`S1`和`S2`两个字符串,如果两个字符串相等则返回0,如果`S1`小于`S2`则返回一个负数,如果`S1`大于`S2`则返回一个正数。
下面是一个使用`strcmp`的示例:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
char str3[] = "hello";
int cmp;
cmp = strcmp(str1, str2);
printf("strcmp(\"%s\", \"%s\") = %d\n", str1, str2, cmp);
cmp = strcmp(str1, str3);
printf("strcmp(\"%s\", \"%s\") = %d\n", str1, str3, cmp);
return 0;
}
```
上述代码中,我们比较了三个字符串`str1`、`str2`、`str3`的大小关系。第一次比较`str1`和`str2`,由于`str1`小于`str2`,所以返回一个负数;第二次比较`str1`和`str3`,由于两个字符串相等,所以返回0。
需要注意的是,`strcmp`函数会比较字符串中的每个字符,直到出现不同的字符或者到达字符串的末尾。因此,如果两个字符串的前缀相同但是后缀不同,那么`strcmp`函数会返回一个非零值。如果需要比较字符串的前缀,可以使用`strncmp`函数。
相关推荐
![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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)