自己strcmp函数
时间: 2023-12-02 19:42:06 浏览: 38
下面是一个简单的自己实现的strcmp函数的例子:
```c
int my_strcmp(const char *s1, const char *s2) {
while (*s1 && (*s1 == *s2)) {
s1++;
s2++;
}
return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}
```
该函数接受两个字符串作为参数,并返回一个整数值,表示两个字符串的大小关系。如果返回值为0,则表示两个字符串相等;如果返回值小于0,则表示第一个字符串小于第二个字符串;如果返回值大于0,则表示第一个字符串大于第二个字符串。
相关问题
strcmp函数用法
strcmp函数是C语言中的字符串比较函数,它用于比较两个字符串是否相等。该函数通常定义在`string.h`头文件中。它的原型是:
```c
int strcmp(const char *str1, const char *str2);
```
参数说明:
- `str1`:第一个要比较的字符串的指针。
- `str2`:第二个要比较的字符串的指针。
返回值:
- 如果`str1`和`str2`相等,返回0。
- 如果`str1`小于`str2`,返回负数(通常是一个整数,表示`str1`在字典序上位于`str2`之前)。
- 如果`str1`大于`str2`,返回正数(同样表示`str1`在字典序上位于`str2`之后)。
使用strcmp函数的一般示例:
```c
if (strcmp(str1, str2) == 0) {
printf("The strings are equal.\n");
} else if (strcmp(str1, str2) < 0) {
printf("str1 is less than str2.\n");
} else {
printf("str1 is greater than str2.\n");
}
```
strcmp函数
strcmp函数是C语言中的字符串比较函数,用于比较两个字符串是否相等。该函数的原型为:
```c
int strcmp(const char *s1, const char *s2);
```
其中,s1和s2是要比较的两个字符串,函数返回值为0时表示两个字符串相等,返回值大于0时表示s1大于s2,返回值小于0时表示s1小于s2。
比如:
```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); // result1 = -15
printf("result2 = %d\n", result2); // result2 = 0
return 0;
}
```
在上面的例子中,str1和str2不相等,比较结果为一个负数;而str1和str3相等,比较结果为0。
相关推荐
![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)