java 指定字符串长度,不足则右侧添加空格

英文字符串 处理

//  指定长度为12 不足 则 右侧拼空格
String.format("%-12s", "qqq")

中文字符串处理

  • 中文字符串在一定的情况下是可以使用上述的英文字符串处理方式处理,但是在某些情况下就不行,例子如下
  • 当要处理多个中文字符串时,切中文字符串的长度都是一样的 如下
System.out.println(String.format("%-12s", "中华") + "|");
System.out.println(String.format("%-12s", "人民") + "|");
System.out.println(String.format("%-12s", "共和") + "|");
// 运行结果 ( | 结束符 方便看)
/**
 * 中华          |
 * 人民          |
 * 共和          |
 */
  • 当长度不一样时 如下:(会看到明显的不同)
System.out.println(String.format("%-12s", "中华") + "|");
System.out.println(String.format("%-12s", "人民") + "|");
System.out.println(String.format("%-12s", "共和国") + "|");
/**
 * 中华          |
 * 人民          |
 * 共和国         |
 */

在这篇博客中找到了解决方案 <<JAVA中文编码和中文字符长度问题和解决方案>>整理如下

/**
 * 设置字符长度  不足者 右侧添加 指定字符
 * @param str1 元字符
 * @param lenth 指定长度
 * @param st2 指定字符
 * @return
 * @throws Exception
 */
public static String strAppendStr(String str1, int lenth, String st2) throws Exception {
	StringBuilder strb1 = new StringBuilder(str1);
	lenth = lenth - getChineseLength(str1, "utf-8");
	while (lenth >= 0) {
		lenth--;
		strb1.append(st2);
	}
	return strb1.toString();
}

/**
 * 计算中文字符长度
 * @param name 字符
 * @param endcoding 编码方式
 * @return
 * @throws Exception
 */
public static int getChineseLength(String name, String endcoding) throws Exception {
	int len = 0; //定义返回的字符串长度
	int j = 0;
	//按照指定编码得到byte[]
	byte[] b_name = name.getBytes(endcoding);
	do {
		short tmpst = (short) (b_name[j] & 0xF0);
		if (tmpst >= 0xB0) {
			if (tmpst < 0xC0) {
				j += 2;
				len += 2;
			} else if ((tmpst == 0xC0) || (tmpst == 0xD0)) {
				j += 2;
				len += 2;
			} else if (tmpst == 0xE0) {
				j += 3;
				len += 2;
			} else {
				short tmpst0 = (short) (((short) b_name[j]) & 0x0F);
				if (tmpst0 == 0) {
					j += 4;
					len += 2;
				} else if (tmpst0 < 12) {
					j += 5;
					len += 2;
				} else {
					j += 6;
					len += 2;
				}
			}
		} else {
			j += 1;
			len += 1;
		}
	} while (j <= b_name.length - 1);
	return len;
}
测试
System.out.println(strAppendStr("中华人民",24,"-")+"|");
System.out.println(strAppendStr("共和国",24,"-")+"|");
中华人民-----------------|
共和国-------------------|
  • 控制台中看度如图 还是有稍微的偏差 不知道什么问题 但是事实是已经对齐了
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

菜鸟阿达

成长总是需要时间和经历的

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

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

打赏作者

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

抵扣说明:

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

余额充值