我在这里和这里都见过类似的问题。
但我不知道如何左垫字符串与零。
输入:“129018” 输出:“0000129018”
总输出长度应为10。
我在这里和这里都见过类似的问题。
但我不知道如何左垫字符串与零。
输入:“129018” 输出:“0000129018”
总输出长度应为10。
当前回答
我更喜欢这样的代码:
public final class StrMgr {
public static String rightPad(String input, int length, String fill){
String pad = input.trim() + String.format("%"+length+"s", "").replace(" ", fill);
return pad.substring(0, length);
}
public static String leftPad(String input, int length, String fill){
String pad = String.format("%"+length+"s", "").replace(" ", fill) + input.trim();
return pad.substring(pad.length() - length, pad.length());
}
}
然后:
System.out.println(StrMgr.leftPad("hello", 20, "x"));
System.out.println(StrMgr.rightPad("hello", 20, "x"));
其他回答
格式化字符串使用
import org.apache.commons.lang.StringUtils;
public class test {
public static void main(String[] args) {
String result = StringUtils.leftPad("wrwer", 10, "0");
System.out.println("The String : " + result);
}
}
输出:字符串:00000wrwer
其中第一个参数是要格式化的字符串,第二个参数是所需输出长度的长度,第三个参数是字符串要填充的字符。
使用链接下载罐子http://commons.apache.org/proper/commons-lang/download_lang.cgi
我更喜欢这样的代码:
public final class StrMgr {
public static String rightPad(String input, int length, String fill){
String pad = input.trim() + String.format("%"+length+"s", "").replace(" ", fill);
return pad.substring(0, length);
}
public static String leftPad(String input, int length, String fill){
String pad = String.format("%"+length+"s", "").replace(" ", fill) + input.trim();
return pad.substring(pad.length() - length, pad.length());
}
}
然后:
System.out.println(StrMgr.leftPad("hello", 20, "x"));
System.out.println(StrMgr.rightPad("hello", 20, "x"));
我用过这个:
DecimalFormat numFormat = new DecimalFormat("00000");
System.out.println("Code format: "+numFormat.format(123));
结果:00123
我希望它对你有用!
Satish的解决方案在预期的答案中是非常好的。我想通过添加变量n到格式化字符串而不是10个字符来使它更通用。
int maxDigits = 10;
String str = "129018";
String formatString = "%"+n+"s";
String str2 = String.format(formatString, str).replace(' ', '0');
System.out.println(str2);
这在大多数情况下都有效
String str = "129018";
String str2 = String.format("%10s", str).replace(' ', '0');
System.out.println(str2);