用指针实现strcmp函数功能
时间: 2024-05-03 15:18:37 浏览: 15
strcmp函数是用来比较两个字符串是否相等的函数,可以使用指针来实现它的功能。
下面是使用指针实现strcmp函数的代码:
```c
int strcmp(const char *s1, const char *s2) {
while (*s1 && (*s1 == *s2)) {
s1++;
s2++;
}
return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}
```
在这个函数中,我们使用了两个指针s1和s2来比较两个字符串。这两个指针分别指向待比较的两个字符串的首字符。
然后,我们使用一个while循环来遍历这两个字符串,直到遇到字符串的结束符'\0'或者两个字符串中有一个字符不相等为止。
最后,我们返回两个指针指向的字符的差值。这里需要注意的是,我们需要将指针转换成无符号字符指针,以保证比较时不会出现负数。
相关问题
利用指针实现strcmp函数功能
好的,利用指针实现strcmp函数的功能可以参考以下代码:
```
int strcmp(const char * str1, const char * str2)
{
while (*str1 && *str1 == *str2) {
++str1;
++str2;
}
return *(const unsigned char *)str1 - *(const unsigned char *)str2;
}
```
该函数的实现通过两个const char型指针str1和str2比较两个字符串的大小,如果str1小于str2,则返回一个负数,如果str1大于str2,则返回一个正数,如果相等则返回0。
需要注意的是,该函数中用到的指针运算符有:*、++、-。其中,*表示取指针所指向的变量值,++表示将指针指向下一个变量,-表示两个指针的地址差值。
用指针实现strcmp
strcmp 是一个用来比较两个字符串的函数。使用指针实现 strcmp,可以通过比较两个字符串的首地址来实现。
下面是一个使用指针实现的 strcmp 函数的例子:
```
int strcmp(char *s1, char *s2) {
while (*s1 != '\0' && *s2 != '\0') {
if (*s1 != *s2) {
return *s1 - *s2;
}
s1++;
s2++;
}
if (*s1 == '\0' && *s2 == '\0') {
return 0;
} else if (*s1 == '\0') {
return -1;
} else {
return 1;
}
}
```
该函数比较两个字符串的每一个字符,如果相同就继续比较下一个字符,如果不同就返回两个字符的 ASCII 码差值,如果其中一个字符串结束了就返回 -1 或 1,如果两个字符串同时结束就返回 0。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)