public static final String replace ( String string , String oldString , String newString ) { if ( string == null ) { return null ; } // If the newString is null or zero length, just return the string since there's nothing // to replace. if ( newString == null ) { return string ; } int i = 0 ; // Make sure that oldString appears at least once before doing any processing. if ( ( i = string . indexOf ( oldString , i ) ) >= 0 ) { // Use char []'s, as they are more efficient to deal with. char [ ] string2 = string . toCharArray ( ) ; char [ ] newString2 = newString . toCharArray ( ) ; int oLength = oldString . length ( ) ; StringBuilder buf = new StringBuilder ( string2 . length ) ; buf . append ( string2 , 0 , i ) . append ( newString2 ) ; i += oLength ; int j = i ; // Replace all remaining instances of oldString with newString. while ( ( i = string . indexOf ( oldString , i ) ) > 0 ) { buf . append ( string2 , j , i - j ) . append ( newString2 ) ; i += oLength ; j = i ; } buf . append ( string2 , j , string2 . length - j ) ; return buf . toString ( ) ; } return string ; }
Replaces all instances of oldString with newString in string .