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. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. System.out.println(replaceSecondOccurrence("aaaa aa", "aa", "bb"));
  13. }
  14.  
  15. public static String replaceSecondOccurrence(String haystack, String needle, String replacement) {
  16. int occurenceToReplace = 2;
  17. int pos = -1;
  18. while (true) {
  19. pos = haystack.indexOf(needle, pos + 1);
  20. if (pos == -1) {
  21. // There is no second occurence. Just return the haystack.
  22. return haystack;
  23. }
  24. if (--occurenceToReplace == 0) return
  25. haystack.substring(0, pos) +
  26. replacement +
  27. haystack.substring(pos + needle.length());
  28. }
  29. }
  30. }
Success #stdin #stdout 0.04s 2184192KB
stdin
Standard input is empty
stdout
abba aa