题目
编写函数实现比较两个字符串字典序大小的功能(不调用标准库函数 strcmp)。若两字符串完全相等输出 0;若第一串大于第二串输出正数;反之输出负数。
输入格式:分两行分别输入两个字符串 s1 和 s2。
输出格式:输出一个整数,表示两串比较结果的差值(或状态 0, 1, -1),末尾换行。
数据范围与约定:字符串长度不超过 500。
思路与算法
1. 逐字符 ASCII 码对比
同步移动两个字符串的指针:当字符相同且未到达结束符时继续前进:while (*s1 && *s1 == *s2) { s1++; s2++; }。
2. 差值返回
遇到第一处不相等的字符或到达末尾时,返回 *(unsigned char*)s1 - *(unsigned char*)s2。转为无符号字符类型避免高位负数扩展导致字典序反转。
完整程序
#include <stdio.h>
// 实现 strcmp 核心逻辑:逐字符比较 ASCII 码,遇到首个不同字符或 '\0' 时停下
static int my_cmp(const char *a, const char *b)
{
while (*a && *b && *a == *b) {
a++;
b++;
}
// 强制转换为 unsigned char,避免出现负数字符比较偏差
return (unsigned char)*a - (unsigned char)*b;
}
int main(void)
{
char a[500], b[500];
if (scanf("%499s %499s", a, b) != 2) {
return 1;
}
printf("%d\n", my_cmp(a, b));
return 0;
}运行示例
输入:
abc abd输出:
-1