public static String replace(String text,String oldsub,String newsub,boolean caseInsensitive,boolean firstOnly){
  StringBuilder buf;
  int tln;
  int oln=oldsub.length();
  if (oln == 0) {
    int nln=newsub.length();
    if (nln == 0) {
      return text;
    }
 else {
      if (firstOnly) {
        return newsub + text;
      }
 else {
        tln=text.length();
        buf=new StringBuilder(tln + (tln + 1) * nln);
        buf.append(newsub);
        for (int i=0; i < tln; i++) {
          buf.append(text.charAt(i));
          buf.append(newsub);
        }
        return buf.toString();
      }
    }
  }
 else {
    oldsub=caseInsensitive ? oldsub.toLowerCase() : oldsub;
    String input=caseInsensitive ? text.toLowerCase() : text;
    int e=input.indexOf(oldsub);
    if (e == -1) {
      return text;
    }
    int b=0;
    tln=text.length();
    buf=new StringBuilder(tln + Math.max(newsub.length() - oln,0) * 3);
    do {
      buf.append(text.substring(b,e));
      buf.append(newsub);
      b=e + oln;
      e=input.indexOf(oldsub,b);
    }
 while (e != -1 && !firstOnly);
    buf.append(text.substring(b));
    return buf.toString();
  }
}

public static String replace ( String text , String oldsub , String newsub , boolean caseInsensitive , boolean firstOnly ) { StringBuilder buf ; int tln ; int oln = oldsub . length ( ) ; if ( oln == 0 ) { int nln = newsub . length ( ) ; if ( nln == 0 ) { return text ; } else { if ( firstOnly ) { return newsub + text ; } else { tln = text . length ( ) ; buf = new StringBuilder ( tln + ( tln + 1 ) * nln ) ; buf . append ( newsub ) ; for ( int i = 0 ; i < tln ; i ++ ) { buf . append ( text . charAt ( i ) ) ; buf . append ( newsub ) ; } return buf . toString ( ) ; } } } else { oldsub = caseInsensitive ? oldsub . toLowerCase ( ) : oldsub ; String input = caseInsensitive ? text . toLowerCase ( ) : text ; int e = input . indexOf ( oldsub ) ; if ( e == - 1 ) { return text ; } int b = 0 ; tln = text . length ( ) ; buf = new StringBuilder ( tln + Math . max ( newsub . length ( ) - oln , 0 ) * 3 ) ; do { buf . append ( text . substring ( b , e ) ) ; buf . append ( newsub ) ; b = e + oln ; e = input . indexOf ( oldsub , b ) ; } while ( e != - 1 && ! firstOnly ) ; buf . append ( text . substring ( b ) ) ; return buf . toString ( ) ; } }
replaces all occurrences of a sub - string in a string .
