我的输入字符串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);
}
答案 0 :(得分:1)
您可以使用String#format(),而使用该方法而不是 replace()的优势在于您可以通过向生成的字符串添加前导零来保留2个位置...
查看此示例并优化它,删除不必要的字符串对象创建...
String patt = "00??00";
for (int i = 0; i < 10; i++) {
String numberWithLeadingZeros = String.format("%02d", i);
String x = String.format(patt.replace("??", "%s"), numberWithLeadingZeros);
System.out.println(x);
}
我们的最终结果将是:
&#34; 000000&#34;&#34; 000100&#34;&#34; 000200&#34; ...&#34; 000900&#34;&#34; 001000&#34 ;, &#34; 001100&#34; ...&#34; 001900&#34; ...&#34; 009900&#34;
答案 1 :(得分:1)
String patter = "00??00";
for (int i = 0; i < 100; i++) {
System.out.println(patt.replace("??", ""+i));
}
答案 2 :(得分:1)
这是一个冗长的解决方案。但它确实有效,
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;
}