更快的可能没有了 不过你可以试试org.apache.commons.lang.StringUtils这个类String test ="3123123";
String value = StringUtils.leftPad(test, 10, "0");
ystem.out.println(value);结果就是0003123123
String value = StringUtils.leftPad(test, 10, "0");
ystem.out.println(value);结果就是0003123123
解决方案 »
- 关于synchronized怎么理解,synchronized锁方法和锁代码块有什么区别?
- [求教高手]将几组数据存入MySQL数据库后显示为空
- 关于synchronized,单例模式
- NoClassDefFoundError vs ClassNotFoundException
- 弱+急 问:java中如何作到如c++中cin的功能?就是可以输入(交互)。
- actionListener怎么传变量出来,请教....
- 串口数据采集的线程问题
- 很基础的问题:字节和字符到底怎样区别阿
- public String和public void有什么不同?
- 弱弱的问一个问题,我怎么可以自动生成一个类似的数组呢?
- LinkedList的一点疑惑
- 求大神解释一下运行结果
package testPackage;public class StringTest {
public static void main(String[] args) {
//假设必须15位长
int fullLength = 15;
//假设输入123456
StringBuilder input = new StringBuilder("123456");
//预先定义一个15位0
StringBuilder zero = new StringBuilder("000000000000000");
String result = zero.substring(0, zero.length() - input.length()) + input;
System.out.println(result);
}
}
String res = String.format("%5s", str);
res = res.replaceAll("\\s", "1");
System.out.println(res);//----------结果:111gr但楼主你还是用二楼提供的方法吧,挺好使的
public class StringTest {
public static String str = "123456789";
private static int length = 20;
public static void addStrLength(){
if(str.length() == length)
return;
str += 0;
addStrLength();
}
public static void main(String[] args) {
addStrLength();
System.out.println(str);
}
}
用递归
public class StringTest {
public static String str = "123456789";
private static int length = 20;
public static void addStrLength(){
if(str.length() == length)
return;
str += 0;
addStrLength();
}
public static void main(String[] args) {
addStrLength();
System.out.println(str);
}
}
public class StringTest {
public static String str = "123456789";
private static int length = 20;
public static void addStrLength(){
if(str.length() == length)
return;
str += 0;
addStrLength();
}
public static void main(String[] args) {
addStrLength();
System.out.println(str);
}
}我光看到你不想用循环了,所以没考虑性能问题,就直接想到了递归,嘿嘿嘿不过就是用的第三方库,它内部实现,也是循环的,或者是用正则,只是封装在StringUtils类里面,对于快速不快速还不好说,不过代码量少了很多,写起来方便了我倒是更赞成四楼的方法
com.google.common.base.Strings.padStart("2010", 3, '0') returns "2010"
另外,如果只是拼0的话还可以考虑(手写,可能有小bug)...
if(remaining > 0) {
char[] originalChars = origin.toCharArray();
char[] chars = new char[poslength];
Arrays.fill(chars, 0, remaining, '0'); // 当然这里也是循环
System.arraycopy(originalChars, 0, chars, 0, length); // 当然这里也涉及循环,但这里不是Java层面的循环,而是底层的指令,速度比较快
return new String(chars);
}
return orgin; // 没必要toString
...
String addStr = "000000000000000";
String srt = "awrawrawr";
String result = addStr+srt;
int length = result.length();
System.out.println(result.substring(length-15,length));这样呢?