/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
	private static String replaceEach(String str, String[] searchWords, String[] replaceWords) {
		int startPos = 0;
		do {
			int matchPos = -1;
			int matchStr = -1;
			for (int i = 0; i < searchWords.length; i++) {
				int pos = str.indexOf(searchWords[i], startPos);
				if (pos == -1) {
					continue;
				}
				if (matchPos == -1 || matchPos > pos) {
					matchPos = pos;
					matchStr = i;
				}
			}
			if (matchPos == -1) {
				break;
			}
			str = str.substring(0, matchPos) + replaceWords[matchStr] + str.substring(matchPos + searchWords[matchStr].length());
			startPos = matchPos + replaceWords[matchStr].length();
		} while (true);
		return str;
	}
	public static void main (String[] args) throws java.lang.Exception
	{
		System.out.println(replaceEach(
		    "Once upon a time, there was a foo and a bar.",
		    new String[]{"foo", "bar"},
		    new String[]{"bar", "foo"}
		));
		System.out.println(replaceEach(
		    "a p",
		    new String[]{"a", "p"},
		    new String[]{"apple", "pear"}
		));
		System.out.println(replaceEach(
		    "ABCDE",
		    new String[]{"A", "B", "C", "D", "E"},
		    new String[]{"B", "C", "E", "E", "F"}
		));
		System.out.println(replaceEach(
		    "ABCDEF",
		    new String[]{"ABCDEF", "ABC", "DEF"},
		    new String[]{"XXXXXX", "YYY", "ZZZ"}
		));
	}
}