這裏的3個解決方法:前兩個是有點算術incrementations而第三個是更多的字符操作。
3個實施方式中的所有傳遞相同的單元測試:
assertEquals("1DDA01A", MyClass.increment("1DDA00Z"));
assertEquals("1A9AV00", MyClass.increment("1A9AU99"));
assertEquals("AFH00", MyClass.increment("AFG99"));
assertEquals("A2GF24", MyClass.increment("A2GF23"));
assertEquals("ABAA0000", MyClass.increment("AAZZ9999"));
assertEquals("11AB0A", MyClass.increment("11AA9Z"));
第一:
public static String increment(String number) {
Pattern compile = Pattern.compile("^(.*?)([9Z]*)$");
Matcher matcher = compile.matcher(number);
String left="";
String right="";
if(matcher.matches()){
left = matcher.group(1);
right = matcher.group(2);
}
number = !left.isEmpty() ? Long.toString(Long.parseLong(left, 36) + 1,36):"";
number += right.replace("Z", "A").replace("9", "0");
return number.toUpperCase();
}
第二:
public static String increment(String number) {
Pattern compile = Pattern.compile("^(.*?)([0-9]*|[A-Z]*)$");
Matcher matcher = compile.matcher(number);
String remaining = number;
String currentGroup = "";
String result = "";
boolean continueToNext = true;
while (matcher.matches() && continueToNext) {
remaining = matcher.group(1);
currentGroup = matcher.group(2);
int currentGroupLength = currentGroup.length();
int base = currentGroup.matches("[0-9]*") ? 10 : 36;
currentGroup = Long.toString(Long.parseLong("1" + currentGroup, base) + 1, base); // The "1" if just to ensure that "000" doesn't become 0 (and thus losing the original string length)
currentGroup = currentGroup.substring(currentGroup.length() - currentGroupLength, currentGroup.length());
continueToNext = Long.valueOf(currentGroup, base) == 0;
if (base == 36) {
currentGroup = currentGroup.replace("0", "A");
}
result = currentGroup + result;
matcher = compile.matcher(remaining);
}
result = remaining + result;
return result.toUpperCase();
}
第三:
這適用於您當前的「需求」。與開頭所提問題相比,這不僅僅是「由字母組成的左半部分」+「由數字組成的右半部分」。現在,這是「任何事情」,字母從A到Z滾動到A,而數字從0到9變爲0.當一個字母到達Z時,它被重置爲A,然後左側的數字/字母增加。
如果所有數字均遞增,則不會在左側添加新數字。你沒有提到你的問題,但我敢肯定,你可以從這裏想出解決辦法:
public static String increment(String number) {
char[] cars = number.toUpperCase().toCharArray();
for (int i = cars.length - 1; i >= 0; i--) {
if (cars[i] == 'Z') {
cars[i] = 'A';
} else if (cars[i] == '9') {
cars[i] = '0';
} else {
cars[i]++;
break;
}
}
return String.valueOf(cars);
}
至於「計數」,你的例子不足以把握邏輯。它只計算數字嗎?那些字母呢?它是否遵循baseXx?
AA010-AAA003 = 7,3 A與2 A不管用嗎? 我覺得這是相當於你明白你的要求(即:作業..)
從技術上講,這回答了最初(最近有很多修改)要求的問題。
我覺得你的意思是'AAA999'是'AAB000',而不是'AAZ000'。另外,這不是基數36,而是基地26的3個地方和基地10的3個地方。根本不清楚你想要做什麼。您需要向我們展示您編寫的代碼並解釋您不瞭解的內容。 –
你看過嗎? http://stackoverflow.com/questions/15735079/convert-from-one-base-to-another-in-java –
不是AAA999之後的值 - > AAA99A在基數36? – alexbt