I recommend the 3rd solution.
Try this.
public static void main(String[] args) {
String string = "Hi$?Hello$?";
String[] rep = {"there", "world"};
String output = string.replaceFirst(
"\\$\\?(.*)\\$\\?", rep[0] + "$1" + rep[1]);
System.out.println(output);
}
output:
HithereHelloworld
Or
static final Pattern PAT = Pattern.compile("\\$\\?");
public static void main(String[] args) {
String string = "Hi$?Hello$?";
String[] rep = {"there", "world"};
int[] i = {0};
String output = PAT.matcher(string).replaceAll(m -> rep[i[0]++]);
System.out.println(output);
}
Or
static final Pattern PAT = Pattern.compile("\\$\\?");
public static void main(String[] args) {
String string = "Hi$?Hello$?";
List<String> rep = List.of("there", "world");
Iterator<String> iter = rep.iterator();
String output = PAT.matcher(string).replaceAll(m -> iter.next());
System.out.println(output);
}