If by "optimal way" you mean performance, then use a loop with indexOf()
and build the result using a StringBuilder
.
Other answers have already covered "simple" (i.e. less code), if that's what you meant by "optimal way".
String input = "The quick * fox jumps * the * dog";
String[] array = {"brown", "over", "lazy"};
StringBuilder buf = new StringBuilder();
int start = 0;
for (int i = 0, idx; i < array.length; i++, start = idx + 1) {
if ((idx = input.indexOf('*', start)) < 0)
break;
buf.append(input.substring(start, idx)).append(array[i]);
}
String output = buf.append(input.substring(start)).toString();
System.out.println(output);
Output
The quick brown fox jumps over the lazy dog
This code will silently accept too many or too few values in the array.