编写mystrcmp的函数实现类似于strcmp的操作
时间: 2023-11-20 22:57:52 浏览: 67
以下是实现类似于strcmp操作的mystrcmp函数的代码实现:
```c
int mystrcmp(char *a, char *b) {
while (*a && *b) {
if (*a > *b) {
return 1;
} else if (*a < *b) {
return -1;
}
a++;
b++;
}
if (*a == *b) {
return 0;
} else {
return (*a > *b) ? 1 : -1;
}
}
```
该函数的实现方式与strcmp函数类似,通过比较两个字符串的每个字符来判断它们的大小关系。如果两个字符相等,则继续比较下一个字符,直到其中一个字符串结束或者两个字符串不相等为止。如果两个字符串都结束了,说明它们相等,返回0;如果其中一个字符串结束了,另一个字符串还有剩余字符,说明它们不相等,返回它们的大小关系。
相关问题
利用指针编程实现函数mystrcmp,实现与库函数strcmp等价的功能
下面是一个利用指针编写的mystrcmp函数的示例代码,其实现与库函数strcmp等价:
```c
int mystrcmp(const char* s1, const char* s2) {
while (*s1 && (*s1 == *s2)) {
s1++;
s2++;
}
return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}
```
该函数接受两个参数,即要比较的两个字符串s1和s2,返回值为整型。函数使用while循环遍历两个字符串,比较它们的每个字符,如果字符相同,指针就向后移动,继续比较下一个字符;如果字符不同,函数就返回它们的ASCII码差值。由于该函数使用了指针,可以避免在函数内部复制字符串,提高了效率。
用c语言编写mystrcmp函数
在 C 语言中,你可以使用 strcmp 函数来比较两个字符串的大小。
它的原型如下:
```
int strcmp(const char *s1, const char *s2);
```
其中,s1 和 s2 分别是要比较的两个字符串。如果 s1 小于 s2,则 strcmp 返回一个负数;如果 s1 等于 s2,则 strcmp 返回 0;如果 s1 大于 s2,则 strcmp 返回一个正数。
例如,你可以使用 strcmp 函数来比较两个字符串的大小:
```
#include <stdio.h>
#include <string.h>
int main()
{
char *s1 = "hello";
char *s2 = "world";
int result = strcmp(s1, s2);
if (result < 0)
printf("%s is less than %s\n", s1, s2);
else if (result > 0)
printf("%s is greater than %s\n", s1, s2);
else
printf("%s is equal to %s\n", s1, s2);
return 0;
}
```
如果你想编写一个自己的 mystrcmp 函数,可以使用以下代码:
```
#include <stdio.h>
int mystrcmp(const char *s1, const char *s2)
{
while (*s1 && (*s1 == *s2))
{
s1++;
s2++;
}
return *s1 - *s2;
}
int main()
{
char *s1 = "hello";
char *s2 = "world";
int result = mystrcmp(s1, s2);
if (result < 0)
printf("%s is less than %s\n", s1, s2);
else if (result > 0)
printf("%s is greater than %s\n", s1, s2);
else
printf("%s is equal to %s\n", s1, s2);
return 0;
}
```
在这个代码中,我们使用一个循环来比较两个字符串的每一个字符。