有一些简单的方法来填充字符串在Java?
似乎是一些应该在一些stringutil类API,但我找不到任何东西,这样做。
有一些简单的方法来填充字符串在Java?
似乎是一些应该在一些stringutil类API,但我找不到任何东西,这样做。
当前回答
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...
其他回答
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
填充到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
*********
除了Apache Commons,还请参阅String。格式,应该能够照顾简单的填充(例如与空格)。
简单的东西:
该值应该是字符串。如果不是,就转换成字符串。比如"" + 123或Integer.toString(123)
// let's assume value holds the String we want to pad
String value = "123";
子字符串从值length 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"