使用compareTo()方法
compareTo()方法介绍:按字母顺序逐个比较字符大小,将字符转换成ASCII码后进行比较,区分字母大小写。
例如:int n1 = str1.compareTo(str2);//比较的是str1和str2的大小,返回两者之间的差值,
如
情况1:str1=“hahb”,str2=“hahc”,则n1= -1(b 和 c 的ASCII码之差);
情况2:str1=“haab”,str2=“hacg”,则n1= -2(a 和 c 的ASCII码之差);
情况3:str1=“hafb”, str2=“haaj”, 则n1= 5(f 和 a 的ASCII码之差);
情况4:str1=“hafb”, str2=“hafb”, 则n1= 0(f 和 f 的ASCII码之差为0);
代码:
import java.util.Scanner;
public class Test {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("请输入第一个字符串:");
String str1 = sc.nextLine();
System.out.print("请输入第一个字符串:");
String str2 = sc.nextLine();
sc.close();
int n1 = str1.compareTo(str2);//比较字符串str1和str2的大小
if ( n1 > 0 )
System.out.println("字符串"+str1+"大于字符串"+str2);
else if ( n1 < 0 )
System.out.println("字符串"+str1+"小于字符串"+str2);
else
System.out.println("字符串"+str1+"等于字符串"+str2);
}
}
运行结果:
请输入第一个字符串:hahk
请输入第一个字符串:hagl
字符串hahk大于字符串hagl
===========================================================
使用compareTocompareToIgnoreCase()方法
compareTocompareToIgnoreCase()方法介绍:按字典比较两个字符串,不区分大小写。
例如:
情况1:str1=“haha”,str2=“HAha”,则n1= 0;
情况2:str1=“haBx”,str2=“hacd”,则n1= -1;
情况3:str1=“sgGc”, str2=“sgdc”, 则n1= 3;
代码:
import java.util.Scanner;
public class Test {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("请输入第一个字符串:");
String str1 = sc.nextLine();
System.out.print("请输入第一个字符串:");
String str2 = sc.nextLine();
sc.close();
int n1 = str1.compareToIgnoreCase(str2);//比较字符串str1和str2的大小
if ( n1 > 0 )
System.out.println("字符串"+str1+"大于字符串"+str2);
else if ( n1 < 0 )
System.out.println("字符串"+str1+"小于字符串"+str2);
else
System.out.println("字符串"+str1+"等于字符串"+str2);
}
}
运行结果:
请输入第一个字符串:agGa
请输入第一个字符串:agbx
字符串agGa大于字符串agbx