I am new to Java and am trying to make a program that will take a string 'names' and replace the names of the people mentioned in that string with a nickname from another string 'replacement'. For instance, "John and Robert were on the way to meet Elizabeth" should return "Joe and Bob were on the way to meet Liz".
My issue is that whenever I run my program, I get multiple sentences back with only one name replaced in each (I'm guessing it is creating a new string each time). Is there a way to avoid this and have it all printed in one sentence? Could I use regex on 'replacement' somehow to fix it?
public static string namereplacer(String names, String replacement) {
String[] toreplace = replacement.split("\t|\n");
for (int i = 0; i <= toreplace.length/2; i++) {
if (i % 2 == 0) { //take even values
fixed; += names.replaceAll(toreplace[i+1],toreplace[i]);
}
}
return fixed;
}
public static void main (String[] args) {
namereplacer("John and Robert were on the way to meet Elizabeth", "John\tJoe\nRobert\tBob\nElizabeth\tLiz");
}
Change the method namereplacer
to this
public static String namereplacer(String names, String replacement) {
String[] toreplace = replacement.split("\n");
for(String str: toreplace){
String [] keyValue = str.split("\t");
if(keyValue.length != 2)
continue;
names = names.replaceAll(keyValue[0], keyValue[1]);
}
return names;
}