Home Search Contact us About us
Title String Search and Replace
Summary This function probably already exist in one of the standard java librarys, but I cant find it. So here is my replacement.
Contributor John McTainsh
Published 7-Feb-2001
Last updated 7-Feb-2001
Page rating   88% for 5 votes Useless Brilliant

Description.

This is nothing more than a simple function to replace text in a java String object. NOTE: If someome knows of a standard function that does this let me know. I would expect there to be on, I just cant find it.

/**
 * Simple string Replace function. Each occurance of "sFrom" is
 * replaced with "sTo".
 * @param sInput    String to search for matches.
 * @param sFrom     String to be replaced by "sTo".
 * @param sTo       String to be inserted in place of "sFrom".
 * @return          Modified string with the new values inserted.
 * @author          john@mctainsg.com
 * @version         1.0 - 6/Feb/2001
 */
public static String Replace( String sInput, String sFrom, String sTo )
{
    StringBuffer sbOut = new StringBuffer();
    int nMatchPos = 0;                                //Location of the start of the match
    int nLastMatchEnd = 0;                            //End of last match
    while( true )
    {
        nMatchPos = sInput.indexOf( sFrom, nLastMatchEnd );
        if( nMatchPos < 0 )
        {
            sbOut.append( sInput.substring( nLastMatchEnd ) ); 
            return sbOut.toString();        
        }
        sbOut.append( sInput.substring( nLastMatchEnd, nMatchPos ) ); 
        sbOut.append( sTo ); 
        nLastMatchEnd = nMatchPos + sFrom.length();
    }
}
Comments Date
Home Search Contact us About us