有一些简单的方法来填充字符串在Java?
似乎是一些应该在一些stringutil类API,但我找不到任何东西,这样做。
有一些简单的方法来填充字符串在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*
其他回答
Apache StringUtils有几个方法:leftPad, rightPad, center和repeat。
但是请注意,正如其他人在这个回答中提到和演示的那样,JDK中的String.format()和Formatter类是更好的选择。使用它们而不是公共代码。
除了Apache Commons,还请参阅String。格式,应该能够照顾简单的填充(例如与空格)。
另一种利用递归的解决方案。
这与所有JDK版本兼容,不需要外部库:
private static String addPadding(final String str, final int desiredLength, final String padBy) {
String result = str;
if (str.length() >= desiredLength) {
return result;
} else {
result += padBy;
return addPadding(result, desiredLength, padBy);
}
}
注意:这个解决方案将附加填充,与一个小调整,你可以前缀填充值。
s =字符串填充 n =期望长度 c = Char到pad
private String padStart( String s, int n, char c ){
if( n <= 0 ) return s;
else return String.format("%" + n + "s", s).replace(' ', c);
}
使用该函数。
private String leftPadding(String word, int length, char ch) {
return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
}
如何使用?
leftPadding(month, 2, '0');
输出: 01 02 03 04 ..11日12