我需要生成递增的字符序列,其中每个字符可以是不同的字母或数字范围。有谁知道这个任务的图书馆?例如:
AAA000_A0
其中A是任何字母A-Z,0是任意数字0-9。我也需要增加它们,例如:
AAA000_A0++ = AAA000_A1
如果你坚持下去,就会继续这样:
AAA000_A9++ = AAA000_B0
直到达到:
ZZZ999_Z9
答案 0 :(得分:3)
我会把问题分解到每个地方,有点像汽车的里程表:
public class CounterDigit {
private final CounterDigit _higher;
private final String _chars;
private int _index = 0;
public CounterDigit(CounterDigit higher, String chars) {
_higher = higher;
_chars = chars;
}
public CounterDigit(CounterDigit higher, char first, char last) {
this(higher, charRange(first, last));
}
private static String charRange(char first, char last) {
StringBuilder b = new StringBuilder();
for (char c = first; c <= last; ++c) {
b.append(c);
}
return b.toString();
}
public char current() {
return _chars.charAt(_index);
}
public void increment() {
if (++_index >= _chars.length()) {
_index = 0;
if (_higher != null) {
_higher.increment();
}
}
}
}
然后,您可以聚合这些的有序序列:
public class Counter {
private CounterDigit[] _digits;
public Counter(String template) {
CounterDigit recent = null;
_digits = new CounterDigit[template.length()];
for (int i = 0; i < template.length(); ++i) {
char c = template.charAt(i);
if (c == 'A') { recent = new CounterDigit(recent, 'A', 'Z'); }
else if (c == '0') { recent = new CounterDigit(recent, '0', '9'); }
else { recent = new CounterDigit(recent, c, c); }
_digits[i] = recent;
}
}
public void increment() {
_digits[_digits.length-1].increment();
}
@Override
public String toString() {
StringBuilder b = new StringBuilder(_digits.length);
for (CounterDigit digit : _digits) {
b.append(digit.current());
}
return b.toString();
}
}
答案 1 :(得分:1)
这是一个简单的算法,短函数就足够了。
这是我在JavaScript中的一个例子。
var _LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var _NUMBERS = "0123456789";
function nextValue(str) {
var result = "";
var carry = true;
var chr, idx, lookup;
for(var i=str.length - 1; i>=0; i--) {
chr = str.charAt(i);
if(carry) {
lookup = _LETTERS.indexOf(chr) >= 0 ? _LETTERS : (_NUMBERS.indexOf(chr) >= 0 ? _NUMBERS : "");
idx = lookup.indexOf(chr);
if(idx >= 0) {
if(idx == lookup.length - 1) {
idx = 0;
} else {
idx++;
carry = false;
}
chr = lookup.charAt(idx);
}
}
result = chr + result;
}
return result;
}
var demo = "0_A";
while(demo != "9_Z") {
demo = nextValue(demo);
console.log(demo);
}
将端口/转换为Java应该很简单,像“indexOf”和“charAt”这样的函数名应该相同。