如何在Java中填充字符串?
1. String.format默认情况下, String.format()用空格\u0020额外填充。通常,我们使用replace()填充其他字符,但是它将替换给定字符串之间的空格。JavaPadString1.java12345678910111213141516171819202122232425262728293031package com.mkyong;public class JavaPadString1 {public static void main(String[] args) {String input = "I Love Java!";// I Love Java!String result1 = String.format("%s", input);// pad 20 charsString result2 = String.format("|%20s|", input); // | I Love Java!|String result3 = String.format("|%-20s|", input); // |I Love Java! |// ********I*Love*Java!String result4 = String.format("%20s", input).replace(" ", "*");// I*Love*Java!********String result5 = String.format("%-20s", input).replace(" ", "*");System.out.println(result1);System.out.println(result2);System.out.println(result3);System.out.println(result4);System.out.println(result5);}}输出量123456789I Love Java!| I Love Java!||I Love Java! |********I*Love*Java!I*Love*Java!********2. Apache Common Lang为了解决上面的String.format问题,我们可以使用Apache Common Lang在字符串的左侧,右侧或中央填充。pom.xml123456789<dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.9</version></dependency>JavaPadString2.java1234567891011121314151617181920212223package com.mkyong;import org.apache.commons.lang3.StringUtils;public class JavaPadString2 {public static void main(String[] args) {String input = "I Love Java!";String result4 = StringUtils.leftPad(input, 20, "*");String result5 = StringUtils.rightPad(input, 20, "*");String result6 = StringUtils.center(input, 20, "*");System.out.println(result4);System.out.println(result5);System.out.println(result6);}}输出量123********I Love Java!I Love Java!************I Love Java!****如果您不想包含用于填充String的库,请深入研究Apache Common Lang StringUtils.leftPad ,然后复制源代码StringUtils.java123456789101112131415161718192021222324252627282930public static String leftPad(final String str, final int size, String padStr) {if (str == null) {return null;}if (isEmpty(padStr)) {padStr = SPACE;}final int padLen = padStr.length();final int strLen = str.length();final int pads = size - strLen;if (pads <= 0) {return str; // returns original String when possible}if (padLen == 1 && pads <= PAD_LIMIT) {return leftPad(str, size, padStr.charAt(0));}if (pads == padLen) {return padStr.concat(str);} else if (pads < padLen) {return padStr.substring(0, pads).concat(str);} else {final char[] padding = new char[pads];final char[] padChars = padStr.toCharArray();for (int i = 0; i < pads; i++) {padding[i] = padChars[i % padLen];}return new String(padding).concat(str);}}以上属于JAVA语言内容, 如果想了解更多的如内容,如, ,,等,包括请关注相关链接