资源限制
时间限制:1.0s 内存限制:512.0MB
独立实现标准字符串库的strcmp函数,即字符串比较函数,从键盘输入两个字符串,按字典序比较大小,前者大于后者输出1,前者小于后者输出-1,两者相等输出0。
样例输入:
apple one
样例输出:
-1
样例输入:
hello he
样例输出:
1
样例输入:
hello hello
样例输出:
0
————————————————————————————————————————————
compareTo():
如果这两个字符串不同,那么它们要么在某个索引处的字符不同(该索引对二者均为有效索引),要么长度不同,或者同时具备这两种情况。如果它们在一个或多个索引位置上的字符不同,假设 k 是这类索引的最小值;则在位置 k 上具有较小值的那个字符串(使用 < 运算符确定),其字典顺序在其他字符串之前。在这种情况下,compareTo 返回这两个字符串在位置 k 处两个char 值的差,即值:
this.charAt(k)-anotherString.charAt(k)
所以,该方法不一定会返回±1。
import java.util.Scanner;
public class Main {
static String str1;
static String str2;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
str1 = sc.next();
str2 = sc.next();
sc.close();
int x = str1.compareTo(str2);
if(x < 0) {
System.out.println(-1);
}else if(x > 0) {
System.out.println(1);
}else {
System.out.println(0);
}
}
}