比较两个字符串的字典顺序

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;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.Letian

您的打赏是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值