编写函数myStrcmp,实现字符串比较的功能
时间: 2023-11-28 20:47:43 浏览: 151
下面是一个简单的实现:
```c
int myStrcmp(char *str1, char *str2) {
int i = 0;
while (str1[i] != '\0' || str2[i] != '\0') {
if (str1[i] != str2[i]) {
return (str1[i] < str2[i]) ? -1 : 1;
}
i++;
}
return 0;
}
```
这个函数会逐个比较两个字符串的字符,直到遇到不同的字符或者其中一个字符串结束。如果遇到不同的字符,就返回它们的 ASCII 码的差值,如果 str1[i] 小于 str2[i],就返回 -1,否则返回 1。如果两个字符串一直都相等,就返回 0。
相关问题
字符串比较函数mystrcmp
my_strcmp()函数是一个自定义的字符串比较函数,用于比较两个字符串的大小。它的实现方式可以根据具体需求进行编写。下面是一个示例实现:
```c
int my_strcmp(const char *str1, const char *str2) {
while (*str1 && (*str1 == *str2)) {
str1++;
str2++;
}
return *(unsigned char*)str1 - *(unsigned char*)str2;
}
```
这个函数会逐个比较两个字符串中的字符,直到遇到不相等的字符或者其中一个字符串结束。如果第一个字符串大于第二个字符串,则返回一个大于0的数;如果两个字符串相等,则返回0;如果第一个字符串小于第二个字符串,则返回一个小于0的数。
采用指针法编写函数mystrcmp(char*t,char+*s),实现伍strcmp的等价功能
根据提供的引用内容,可以了解到strcmp函数是用于比较两个字符串的函数,如果两个字符串相等,则返回0,如果第一个字符串小于第二个字符串,则返回负数,如果第一个字符串大于第二个字符串,则返回正数。下面是使用指针法编写的mystrcmp函数的代码实现:
```c
int mystrcmp(char* t, char* s) {
while (*t && *s && (*t == *s)) {
t++;
s++;
}
return *t - *s;
}
```
在这个函数中,我们使用while循环来比较两个字符串,如果两个字符串的当前字符相等,则继续比较下一个字符,直到遇到不相等的字符或者其中一个字符串结束。最后,我们返回两个字符串第一个不相等字符的ASCII码差值。
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)