2014-08-30 2 views
-3

얘들 아 내가이 아이디 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을 추가로 반환하는 방법을 물어 0을 놓치지 않고 문자열? TIA :

+2

String.printf를 살펴보십시오. 또는 MessageFormat. – bmargulies

+1

'ABCD'와'XYZL'은 항상 같습니까? 당신은 하드 코딩 했습니까? –

+0

예 하드 코딩 됨 –

답변

1

이 형식의

  • 4 글자
  • 9 숫자
  • 4 글자

당신은 정규식, 수를 증가 사용하여 분석 할 수있다, 다음을 다시 빌드합니다. 이런 식으로 뭔가 : 당신은 코드가 조금 짧게하는 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); 
    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); 
    } 
} 

; 복잡성의 대가로 :

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

고맙습니다. 매우 많이 :) –

0

당신처럼 난 당신이 자신의

0

당신은 String.format(String, Object...)이 같은 것을 사용할 수 있습니다 당신의 세부 사항을 알아낼 수 확신 DecimalFormat 봐,

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++); 
    } 
} 

실행할 수 있나요 D

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 
0 id 가정
관련 문제