Reputation: 1182
For example: I have a string mask with length = 5 symbols and I have a value with length = 3 symbols. All combinations are:
val__, _val_, __val
another example for mask length = 3, value length = 2:
xx_, _xx
How to generate these masks programmatically? For example in method with following signature: String[] generateMasks(int maskLength, String val);
My attempts:
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;
}
Maybe are there more elegant solutions for this?
Upvotes: 1
Views: 1098
Reputation: 36703
Example
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;
}
Output
[val__, _val_, __val]
[xx_, _xx]
Upvotes: 1