例如: 我有一个长度= 5个符号的字符串掩码,我有一个长度= 3个符号的值。 所有组合均为:
val__, _val_, __val
掩码长度= 3,值长度= 2的另一个例子:
xx_, _xx
如何以编程方式生成这些掩码? 例如,在具有以下签名的方法中: String [] generateMasks(int maskLength,String val);
我的尝试:
private ArrayList<String> maskGenerator2(int from, char[] value) {
ArrayList<String> result = new ArrayList<String>();
//initial position
char[] firstArray = new char[from];
for (int i=0; i<from; i++) {
if (i < value.length) firstArray[i] = value[i];
else firstArray[i] = '_';
}
result.add(String.valueOf(firstArray));
System.out.println(firstArray);
//move value
int k = 0;
while (k < from - value.length) {
char last = firstArray[from - 1];
for (int i = from - 1; i > 0; i--) {
firstArray[i] = firstArray[i - 1];
}
firstArray[0] = last;
result.add(String.valueOf(firstArray));
System.out.println(firstArray);
k++;
}
return result;
}
也许有更优雅的解决方案吗?
答案 0 :(得分:1)
实施例
public static void main(String[] args) throws Exception {
System.out.println(createMask(5, "val"));
System.out.println(createMask(3, "xx"));
}
private static List<String> createMask(int length, String value) {
List<String> list = new ArrayList<String>();
String base = new String(new char[length]).replace("\0", "_");
for (int offset = 0; offset <= length - value.length(); offset++) {
StringBuilder buffer = new StringBuilder(base);
buffer.replace(offset, offset + value.length(), value);
list.add(buffer.toString());
}
return list;
}
输出
[val__, _val_, __val]
[xx_, _xx]