import java.util.Scanner;
/**
* @ClassName: StringCompare
* @Description:比较两个字符串的字典顺序
* @Author: Wanglt
* @CreateDate: 2020年2月24日
*
*/
public class StringCompare {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("------------开始------------");
System.out.println("请输入字符串A");
String a = in.nextLine();
System.out.println("请输入字符串B");
String b = in.nextLine();
System.out.println("不考虑大小写:" + func(a, b, false));
System.out.println("考虑大小写(大写小于小写):" + func(a, b, true));
System.out.println("------------结束------------\n");
}
}
/**
* 如果要比较两个字符串的字典顺序,如何实现?能否用>、<? 注:大写小于小写(几个常见字母的ASCII码大小: “A”为65;“a”为97;“0”为 48)
*
* @param a
* @param b
* @param considerCase 是否考虑大小写
* @return
*/
public static String func(String a, String b, boolean considerCase) {
if (a == null || b == null || a.isEmpty() || b.isEmpty()) {
return "异常,存在字符串为空";
}
if (!considerCase) {
a = a.toLowerCase();
b = b.toLowerCase();
}
String res = "";
char[] ca = a.toCharArray();
char[] cb = b.toCharArray();
// 可能情况
String situation1 = "字符串A在字符串B前";
String situation2 = "字符串B在字符串A前";
String situation3 = "字典序一样";
// 选取最小长度
int minlength = ca.length <= cb.length ? ca.length : cb.length;
// 比较
for (int i = 0; i < minlength; i++) {
if (ca[i] < cb[i]) {
res = situation1;
return res;
} else if (ca[i] > cb[i]) {
res = situation2;
return res;
}
}
if (ca.length == cb.length) {
return situation3;
}
if ("".equals(res)) {
res = ca.length == minlength ? situation1 : situation2;
}
return res;
}
}
比较两个字符串的字典顺序
最新推荐文章于 2024-08-06 22:57:02 发布