题目
编写函数实现比较两个字符串字典序大小的功能(不调用标准库函数 strcmp)。若两字符串完全相等输出 0;若第一串大于第二串输出正数;反之输出负数。
输入格式:分两行分别输入两个字符串 s1 和 s2。
输出格式:输出一个整数,表示两串比较结果的差值(或状态 0, 1, -1),末尾换行。
数据范围与约定:字符串长度不超过 500。
思路与算法
1. 逐字符 ASCII 码对比
同步移动两个字符串的指针:当字符相同且未到达结束符时继续前进:while (*s1 && *s1 == *s2) { s1++; s2++; }。
2. 差值返回
遇到第一处不相等的字符或到达末尾时,返回 *(unsigned char*)s1 - *(unsigned char*)s2。转为无符号字符类型避免高位负数扩展导致字典序反转。
完整程序
import java.util.Scanner;
public class Main {
// 模拟 strcmp:逐字符比较 ASCII 码差值
public static int myStrcmp(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
int minLen = Math.min(len1, len2);
for (int i = 0; i < minLen; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 != c2) {
return c1 - c2;
}
}
return len1 - len2;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.next();
String s2 = sc.next();
System.out.println(myStrcmp(s1, s2));
}
}运行示例
输入:
abc abd输出:
-1