我输入的字符串uid包含6个字符,有0~6个'?'在随机位置,如“00??00”、“0?00?0”、“0??00?”。例如,如果输入是“00?0?0”,我想替换两个“?”与0~9。所以结果应该是"000000","000010","000020"..."000090","001000","001010"..."001090"..."009090"
好吧,我下面的代码只能得到"000000","001010","002020"..."009090"
,我知道replace()会替换所有'?' ,并且使用replaceFirst()可能会解决这个问题。那么如何使用replaceFirst()来得到我想要的结果呢?
List<Get> gets = new ArrayList<>();
for (int i =0; i<10; i++){
get = new Get((uid.replace(uid.charAt(2), (char) (i + '0'))).getBytes());
// get = new Get((uid.replaceFirst("\\?", "0+i")).getBytes());
gets.add(get);
}
最佳答案
这是一个冗长的解决方案。但它确实有效,
public static void main(String[] args) {
String patt = "0?0?00";
List<String> a = new ArrayList<>();
a.add(patt);
while (true) {
List<String> b = generateAndGet(a);
if (b.size() == 0) {
break;
}
a = b;
}
for (String item : a) {
System.out.println(item);
}
return;
}
private static List<String> generateAndGet(List<String> val) {
List<String> result = new ArrayList<String>();
for (String item : val) {
final char[] itemArray = item.toCharArray();
for (int i = 0; i < itemArray.length; i++) {
if (itemArray[i] == '?') {
for (int j = 0; j < 10; j++) {
itemArray[i] = (char) (j + '0');
result.add(String.copyValueOf(itemArray));
}
}
}
}
return result;
}
关于java - 在我的例子中如何使用replaceFirst()来获取一系列连续的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43111436/