strcmp函数是如何比较两个字符串的?
时间: 2024-06-16 20:06:29 浏览: 21
strcmp函数是C语言中用于比较两个字符串的函数。它的原型定义在<string.h>头文件中,函数的声明如下:
int strcmp(const char *str1, const char *str2);
该函数接受两个参数,分别是要比较的两个字符串str1和str2。它会按照字典序逐个比较两个字符串中对应位置的字符,直到遇到不同的字符或者其中一个字符串结束为止。
具体比较规则如下:
- 如果两个字符串相等,返回值为0。
- 如果str1大于str2,返回值大于0。
- 如果str1小于str2,返回值小于0。
strcmp函数会根据ASCII码值来比较字符,因此它是区分大小写的。如果需要进行不区分大小写的比较,可以使用strcasecmp函数。
相关问题
使用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
自定义一个strcmp函数实现两个字符串比较
好的,以下是一个简单的strcmp函数的实现:
```
int my_strcmp(const char* str1, const char* str2) {
int i = 0;
while (str1[i] != '\0' && str2[i] != '\0') {
if (str1[i] < str2[i])
return -1;
else if (str1[i] > str2[i])
return 1;
i++;
}
if (str1[i] == str2[i])
return 0;
else if (str1[i] < str2[i])
return -1;
else
return 1;
}
```
此函数将两个字符串逐个字符进行比较,如果相同则继续比较直到其中一个字符串结束,如果两个字符串相等则返回0,如果前一个字符串小于后一个字符串则返回负数,反之则返回正数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)