code: public static String replace(String text, String repl, String with, int max) {
          if (text == null) {
              return null;
          }
  
          StringBuffer buf = new StringBuffer(text.length());
          int start = 0, end = 0;
          while ((end = text.indexOf(repl, start)) != -1) {
              buf.append(text.substring(start, end)).append(with);
              start = end + repl.length();
  
              if (--max == 0) {
                  break;
              }
          }
          buf.append(text.substring(start));
          return buf.toString();
      }
docs: Replace a string with another string inside a larger string, for the
  first <code>max</code> values of the search string. A <code>null</code>
  reference is passed to this method is a no-op.
  
  @param text
  text to search and replace in
  @param repl
  String to search for
  @param with
  String to replace with
  @param max
  maximum number of values to replace, or <code>-1</code> if no
  maximum
  @return the text with any replacements processed