This should work:
public static String replace(String phrase, String before, String after, int index) {
String[] splittedPhrase = phrase.split(" ");
String output = "";
for (int i = 0, j = 0; i < splittedPhrase.length; i++) {
if (i != 0)
output += " ";
if (splittedPhrase[i].equals(before) && index == j++)
output += after;
else
output += splittedPhrase[i];
}
return output;
}
Or, in a shorter way:
public static String replace(String phrase, String before, String after, int index) {
int i = 0;
String output = "";
for (String s : phrase.split(" "))
output += ((s.equals(before) && index == i++) ? after : s) + " ";
return output.substring(0, output.length() - 1);
}
Then, simply:
public static void main(String args[]) {
System.out.println(replace("hello world, hello", "hello", "goodbye", 0));
System.out.println(replace("hello world, hello", "hello", "goodbye", 1));
System.out.println(replace("hello world, hello", "hello", "goodbye", 2));
}
Printed out:
"goodbye world, hello"
"hello world, goodbye"
"hello world, hello"