本帖最后由 舒远 于 2012-9-13 17:30 编辑
- /**
- * 三种实现字符串前面补零的算法
- */
- public class RegTest {
- public static void main(String[] args) {
- System.out.println(replace("123", 10));
- System.out.println(addByLength("111222333", 10));
- System.out.println(recursion ("123", 10));
- }
-
- public static String replace(String no, int a) {
- String str = no;
- String zero = "";
- for (int i = 0; i < a; i++) {
- zero += "0";
- }
- return str.replaceAll("(\\d+)", zero + "$1").replaceAll("0*(\\d{" + a + "})", "$1");
- }
-
- public static String addByLength(String a, int b) {
- String r = a;
- int len = b - r.length();
- for (int i = 0; i < len; i++) {
- r = "0" + r;
- }
- return r;
- }
-
- public static String recursion(String a, int b) {
- if (b <= a.length())
- return a;
- else {
- return "0" + recursion(a, --b);
- }
- }
- }
复制代码 各位若有其他算法,还请不吝回帖 |