编写一个函数实现strcmpy
时间: 2023-11-15 17:50:52 浏览: 32
好的,我可以为您编写一个实现字符串比较的函数。以下是一个简单的示例代码:
```c
#include <stdio.h>
int strcmpy(const char* str1, const char* str2) {
while (*str1 && (*str1 == *str2)) {
str1++;
str2++;
}
return *(unsigned char*)str1 - *(unsigned char*)str2;
}
int main() {
const char* str1 = "Hello";
const char* str2 = "World";
int result = strcmpy(str1, str2);
if (result < 0) {
printf("str1 is less than str2\n");
} else if (result > 0) {
printf("str1 is greater than str2\n");
} else {
printf("str1 is equal to str2\n");
}
return 0;
}
```
这个函数通过逐个比较两个字符串中的字符来确定它们是否相等。如果两个字符串相等,函数返回0;如果第一个字符串小于第二个字符串,函数返回一个负数;如果第一个字符串大于第二个字符串,函数返回一个正数。在上面的示例中,"Hello" 小于 "World",所以输出结果是 "str1 is less than str2"。