英文字符串 处理
// 指定长度为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,"-")+"|");
中华人民-----------------|
共和国-------------------|
- 控制台中看度如图 还是有稍微的偏差 不知道什么问题 但是事实是已经对齐了