用指针变量编写字符串比较函数
时间: 2023-11-30 14:03:09 浏览: 36
下面是用指针变量编写字符串比较函数的示例代码:
```c
#include <stdio.h>
int strcmp(char *s1, char *s2) {
int i = 0;
while (s1[i] != '\0' && s2[i] != '\0') {
if (s1[i] < s2[i]) {
return -1;
} else if (s1[i] > s2[i]) {
return 1;
}
i++;
}
if (s1[i] == '\0' && s2[i] == '\0') {
return 0;
} else if (s1[i] == '\0') {
return -1;
} else {
return 1;
}
}
int main() {
char str1[] = "hello";
char str2[] = "world";
int result = strcmp(str1, str2);
printf("result: %d\n", result);
return 0;
}
```
在上面的代码中,strcmp函数接收两个指向字符数组的指针变量s1和s2作为参数,用于比较两个字符串。函数使用while循环遍历两个字符串中的每个字符,逐个比较它们的ASCII码值。如果两个字符不同,则函数根据它们的大小关系返回-1或1。如果两个字符串的长度相等且每个字符都相同,则函数返回0。如果s1比s2短,则函数返回-1;如果s1比s2长,则函数返回1。最后,在main函数中调用strcmp函数,将其结果打印到控制台。