qfedu-c-level/day11/d13.c

34 lines
825 B
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 比较两个字符串,如果 s1 > s2返回 1如果 s1 < s2返回 -1如果 s1 == s2返回 0
int cmp(const char *s1, const char *s2)
{
while (*s1 && *s2)
{
if (*s1 > *s2) // 当前位置 *s1 > *s2
return 1;
else if (*s1 < *s2) // 当前位置 *s1 < *s2
return -1;
else // *s1 == *s2
{
s1++; // s1 指向下一个字符
s2++; // s2 指向下一个字符
}
}
if (*s1) // *s1 还有字符,*s2 没有字符
return 1;
if (*s2) // *s2 还有字符,*s1 没有字符
return -1;
return 0; // *s1 == *s2返回相等
}
int main()
{
char *p = "abc";
char *q = "abcd";
printf("%d\n", cmp(p, q));
return 0;
}