2014-08-30 39 views
-3

嗨,我有這個ID ABCD000000001XYZL我怎樣才能使,增加了每次但犯規刪除零(0)

public class SmartCounter { 
public String SmartCounter(String strID){ 
intNumber =Integer.parseInt(strID.replaceAll("\\D+","")); 
intNumber += 1; 
strReturn = "ABCD"+intNumber+"XYZL"; 
(strReturn);   
} 
} 
的ID

我只是問我如何能加1到數字的一部分,它返回到一個字符串不丟失零? TIA:d

+2

看看String.printf。或MessageFormat。 – bmargulies 2014-08-30 20:26:12

+1

「ABCD」和「XYZL」總是相同的 - 你有硬編碼嗎? – 2014-08-30 20:31:23

+0

是的這是硬編碼 – 2014-08-31 04:42:56

回答

1

假設id的格式爲

  • 4個字母
  • 9號
  • 4個字母

可以使用正則表達式,遞增數解析它,然後重建。事情是這樣的:

public static void main(String[] args) throws Exception { 
    final Pattern pattern = Pattern.compile("(\\D{4})(\\d{9})(\\D{4})"); 
    final String input = "ABCD000000001XYZL"; 
    final Matcher matcher = pattern.matcher(input); 
    if (matcher.matches()) { 
     final String head = matcher.group(1); 
     final long number = Long.parseLong(matcher.group(2)) + 1; 
     final String tail = matcher.group(3); 
     final String result = String.format("%s%09d%s", head, number, tail); 
     System.out.println(result); 
    } 
} 

您可以使用正則表達式snazzier和Matcher.appendReplacement使代碼短一點;代價是複雜性:

public static void main(String[] args) throws Exception { 
    final Pattern pattern = Pattern.compile("(?<=\\D{4})(\\d{9})(?=\\D{4})"); 
    final String input = "ABCD000000001XYZL"; 
    final Matcher matcher = pattern.matcher(input); 
    final StringBuffer result = new StringBuffer(); 
    if (matcher.find()) { 
     final long number = Long.parseLong(matcher.group(1)) + 1; 
     matcher.appendReplacement(result, String.format("%09d", number)); 
    } 
    matcher.appendTail(result); 
    System.out.println(result); 
} 
+0

謝謝非常多:)) – 2014-08-31 04:50:21

0

你可以使用String.format(String, Object...)和這樣的事情,

class SmartCounter { 
    private int id = 1; 

    public SmartCounter() { 
     this.id = 1; 
    } 

    public SmartCounter(int id) { 
     this.id = id; 
    } 

    public String smartCounter() { 
     return String.format("ABCD%09dXYZL", id++); 
    } 
} 

,你可以運行像

public static void main(String[] args) { 
    SmartCounter sc = new SmartCounter(); 
    for (int i = 0; i < 3; i++) { 
     System.out.println(sc.smartCounter()); 
    } 
} 

輸出是

ABCD000000001XYZL 
ABCD000000002XYZL 
ABCD000000003XYZL