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