网络公司网站建广告营销推广方案
String.format("xxxx%6sxxxxx", "111")//是将中间的%6s进行替换,如果替换字符不足6会填充空格,空格是根据系统来的
改成指定以中文填充
public class StringFormatUtils {public static String format(String s, String... args) {if (args == null || args.length == 0) {return s;}StringBuffer sb = new StringBuffer();Pattern p = Pattern.compile("(%\\d+?s)");Matcher matcher = p.matcher(s);int index = -1;while (matcher.find()) {int groupCount = matcher.groupCount();if (groupCount < 1) {continue;}String group1 = matcher.group(1);Pattern p2 = Pattern.compile("^%(\\d+?)s$");Matcher matcher1 = p2.matcher(group1);int n = 0;if (matcher1.find()) {n = Integer.valueOf(matcher1.group(1));}String replacement = fillSpace(args[++index], n);matcher.appendReplacement(sb, replacement);}matcher.appendTail(sb);return sb.toString();}public static double len(String s) {double len = 0;for (int i = 0; i < s.length(); i++) {String str = s.substring(i, i + 1);if (str.matches("[0-9A-Za-z\\.\\+\\-%]")) {len += 0.5;} else {len += 1;}}return len;}public static String fillSpace(String s, int fullLen) {return fillSpace(s, fullLen, true, false);}public static String fillSpace(String s, int fullLen, boolean debug) {return fillSpace(s, fullLen, true, debug);}public static String fillSpace(String s, int fullLen, boolean left, boolean debug) {double len = len(s);if (len >= fullLen) {return s;}StringBuilder s1 = new StringBuilder(s);while (len(s1.toString()) < fullLen) {double diff = fullLen - len(s1.toString());String zhspace = debug ? "空" : " ";String enspace = debug ? "s" : " ";if (diff == 0.5d) {if (left) {s1.insert(0, enspace);} else {s1.append(enspace);}} else {if (left) {s1.insert(0, zhspace);} else {s1.append(zhspace);}}}return s1.toString();}
测试代码
System.out.println(StringFormatUtils.format(s, "sss"));System.out.println(StringFormatUtils.format(s, "dd你你"));System.out.println(StringFormatUtils.format(s, "+10%"));System.out.println(StringFormatUtils.format(s, "-150%"));System.out.println("--------------------------------");System.out.println(String.format(s, "sss"));System.out.println(String.format(s, "dd你你"));System.out.println(String.format(s, "+10%"));System.out.println(String.format(s, "-150%"));
输出
这里发现改了之后,对齐效果仍然不是特别完美。但是比原生的还是好一点,原生的除非说输入的字符串规则完全一致,否则一旦遇到中英文混杂的情况,对齐效果感观上差异比较大。