fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. private static String replaceEach(String str, String[] searchWords, String[] replaceWords) {
  11. int startPos = 0;
  12. do {
  13. int matchPos = -1;
  14. int matchStr = -1;
  15. for (int i = 0; i < searchWords.length; i++) {
  16. int pos = str.indexOf(searchWords[i], startPos);
  17. if (pos == -1) {
  18. continue;
  19. }
  20. if (matchPos == -1 || matchPos > pos) {
  21. matchPos = pos;
  22. matchStr = i;
  23. }
  24. }
  25. if (matchPos == -1) {
  26. break;
  27. }
  28. str = str.substring(0, matchPos) + replaceWords[matchStr] + str.substring(matchPos + searchWords[matchStr].length());
  29. startPos = matchPos + replaceWords[matchStr].length();
  30. } while (true);
  31. return str;
  32. }
  33. public static void main (String[] args) throws java.lang.Exception
  34. {
  35. System.out.println(replaceEach(
  36. "Once upon a time, there was a foo and a bar.",
  37. new String[]{"foo", "bar"},
  38. new String[]{"bar", "foo"}
  39. ));
  40. System.out.println(replaceEach(
  41. "a p",
  42. new String[]{"a", "p"},
  43. new String[]{"apple", "pear"}
  44. ));
  45. System.out.println(replaceEach(
  46. "ABCDE",
  47. new String[]{"A", "B", "C", "D", "E"},
  48. new String[]{"B", "C", "E", "E", "F"}
  49. ));
  50. System.out.println(replaceEach(
  51. "ABCDEF",
  52. new String[]{"ABCDEF", "ABC", "DEF"},
  53. new String[]{"XXXXXX", "YYY", "ZZZ"}
  54. ));
  55. }
  56. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
Once upon a time, there was a bar and a foo.
apple pear
BCEEF
XXXXXX