是否有一些简单的方法来填充Java中的字符串?
看起来像某些类似于StringUtil的API,但我找不到任何可以做到这一点的东西.
从Java 1.5开始,String.format()
可以用左/右垫填充给定的字符串.
public static String padRight(String s, int n) { return String.format("%-" + n + "s", s); } public static String padLeft(String s, int n) { return String.format("%" + n + "s", s); } ... public static void main(String args[]) throws Exception { System.out.println(padRight("Howto", 20) + "*"); System.out.println(padLeft("Howto", 20) + "*"); }
输出是:
Howto * Howto*
填充到10个字符:
String.format("%10s", "foo").replace(' ', '*'); String.format("%-10s", "bar").replace(' ', '*'); String.format("%10s", "longer than 10 chars").replace(' ', '*');
输出:
*******foo bar******* longer*than*10*chars
显示密码字符'*':
String password = "secret123"; String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');
输出与密码字符串的长度相同:
secret123 *********
阿帕奇StringUtils
有几种方法:leftPad
,rightPad
,center
和repeat
.
但请注意 - 正如其他人在本回答中提到并证明的那样- String.format()
并且Formatter
JDK中的类是更好的选择.在公共代码上使用它们.
在番石榴,这很容易:
Strings.padStart("string", 10, ' '); Strings.padEnd("string", 10, ' ');
简单的东西:
该值应为字符串.将其转换为字符串,如果不是.喜欢"" + 123
或Integer.toString(123)
// let's assume value holds the String we want to pad String value = "123";
子字符串从值长度char索引开始直到填充的结束长度:
String padded="00000000".substring(value.length()) + value; // now padded is "00000123"
更确切
垫右:
String padded = value + ("ABCDEFGH".substring(value.length())); // now padded is "123DEFGH"
垫左:
String padString = "ABCDEFGH"; String padded = (padString.substring(0, padString.length() - value.length())) + value; // now padded is "ABCDE123"
看看org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar)
.
但算法非常简单(填充到大小字符):
public String pad(String str, int size, char padChar) { StringBuffer padded = new StringBuffer(str); while (padded.length() < size) { padded.append(padChar); } return padded.toString(); }
除了Apache Commons之外,还要看String.format
哪些应该能够处理简单的填充(例如,使用空格).
public static String LPad(String str, Integer length, char car) { return (str + String.format("%" + length + "s", "").replace(" ", String.valueOf(car))).substring(0, length); } public static String RPad(String str, Integer length, char car) { return (String.format("%" + length + "s", "").replace(" ", String.valueOf(car)) + str).substring(str.length(), length + str.length()); } LPad("Hi", 10, 'R') //gives "RRRRRRRRHi" RPad("Hi", 10, 'R') //gives "HiRRRRRRRR" RPad("Hi", 10, ' ') //gives "Hi " RPad("Hi", 1, ' ') //gives "H" //etc...
我花了一点时间才弄明白.真正的关键是阅读Formatter文档.
// Get your data from wherever. final byte[] data = getData(); // Get the digest engine. final MessageDigest md5= MessageDigest.getInstance("MD5"); // Send your data through it. md5.update(data); // Parse the data as a positive BigInteger. final BigInteger digest = new BigInteger(1,md5.digest()); // Pad the digest with blanks, 32 wide. String hex = String.format( // See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html // Format: %[argument_index$][flags][width]conversion // Conversion: 'x', 'X' integral The result is formatted as a hexadecimal integer "%1$32x", digest ); // Replace the blank padding with 0s. hex = hex.replace(" ","0"); System.out.println(hex);
我知道这个线程有点陈旧,最初的问题是一个简单的解决方案,但如果它应该非常快,你应该使用一个char数组.
public static String pad(String str, int size, char padChar) { if (str.length() < size) { char[] temp = new char[size]; int i = 0; while (i < str.length()) { temp[i] = str.charAt(i); i++; } while (i < size) { temp[i] = padChar; i++; } str = new String(temp); } return str; }
格式化程序解决方案不是最佳的.只需构建格式字符串即可创建2个新字符串.
apache的解决方案可以通过初始化目标大小的sb来改进,以便在下面替换
StringBuffer padded = new StringBuffer(str);
同
StringBuffer padded = new StringBuffer(pad); padded.append(value);
会阻止某人的内部缓冲增长.
这是另一种填充到右侧的方法:
// put the number of spaces, or any character you like, in your paddedString String paddedString = "--------------------"; String myStringToBePadded = "I like donuts"; myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length()); //result: myStringToBePadded = "I like donuts-------";