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

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;
	}
}
要对n个字符串按照字典顺序进行排序,可以使用C标准库中的qsort函数,并编写一个自定义的比较函数。以下是一个示例程序: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LEN 100 // 最大字符串长度 #define MAX_NUM 100 // 最大字符串数量 int cmp(const void *a, const void *b) { return strcmp(*(const char **)a, *(const char **)b); } int main(void) { char *strs[MAX_NUM]; // 存储指向字符串的指针 int n; // 字符串数量 // 读入字符串 printf("请输入字符串数量:"); scanf("%d", &n); printf("请输入%d个字符串(每行一个):\n", n); for (int i = 0; i < n; i++) { char *str = (char *)malloc(MAX_LEN * sizeof(char)); // 分配字符串内存 scanf("%s", str); strs[i] = str; // 记录指针 } // 排序 qsort(strs, n, sizeof(char *), cmp); // 输出结果 printf("按字典顺序排序后的结果为:\n"); for (int i = 0; i < n; i++) { printf("%s\n", strs[i]); free(strs[i]); // 释放字符串内存 } return 0; } ``` 在上述程序中,我们定义了一个自定义的比较函数cmp,它接受两个指向字符串的指针,使用strcmp函数进行比较并返回比较结果。然后在主函数中,我们使用指针数组strs存储指向字符串的指针、读入字符串、调用qsort函数进行排序、输出结果,并在最后释放字符串内存。需要注意的是,在使用malloc函数分配字符串内存后,需要在程序结束前使用free函数释放内存,以免出现内存泄漏的问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Mr.Letian

您的打赏是我最大的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值