Java tutorial
//package com.java2s; public class Main { /** /* StrFindAndReplace - finds and replaces all in String theString. * * @param findString, replaceString, origString * @return finalString * */ public static String StrFindAndReplace(String find, String replace, String theString) { if (theString.length() == 0) return ""; if (find.length() == 0) return theString; if (find.equals(replace)) return theString; StringBuffer theBuf = new StringBuffer(theString); int found = 0; int iSearchFrom = 0; while (found != -1) { found = FindAndReplace(find, replace, theBuf, iSearchFrom); iSearchFrom = found + replace.length(); } return theBuf.toString(); } /** /* FindAndReplace - finds and replaces in StringBuffer theSBuffer, /* starts at fromIndex, returns index of find. * * @param findString, replaceString, sBuffer, index * @return int * */ public static int FindAndReplace(String find, String replace, StringBuffer theSBuffer, int fromIndex) { String interString; int theIndex, i, j; if (find == null) return -1; if (replace == null) return -1; if (theSBuffer == null) return -1; int theSBufferLength = theSBuffer.length(); int findLength = find.length(); if (theSBufferLength == 0) return -1; if (findLength == 0) return -1; if (theSBufferLength < findLength) return -1; if ((fromIndex < 0) || (fromIndex > theSBufferLength)) return -1; interString = theSBuffer.toString(); theIndex = interString.indexOf(find, fromIndex); if (theIndex == -1) return -1; //// on 9210 the following code ... for (i = theIndex; i < theSBufferLength - findLength; i++) { theSBuffer.setCharAt(i, theSBuffer.charAt(i + findLength)); } for (j = theSBufferLength - 1; j >= (theSBufferLength - findLength); j--) { theSBuffer.setCharAt(j, (char) (0)); } int newLength = theSBufferLength - findLength; theSBuffer.setLength(newLength); theSBuffer.insert(theIndex, replace); return theIndex; } }