public static String replaceStringNew(String line, String oldstr, String newstr) { StringBuffer sb = null; int oldLen = oldstr.length(); if (oldLen == 0) { return line; } if (oldLen == newstr.length()) { if (oldstr.equals(newstr)) { return line; } sb = new StringBuffer(line); int prevIdx = 0; while ((prevIdx = line.indexOf(oldstr, prevIdx)) >= 0) { sb.replace(prevIdx, prevIdx + oldLen, newstr); prevIdx += oldLen; } } else { int lineLen = line.length(); sb = new StringBuffer(lineLen); int oldIdx = 0; int thisIdx; while ((thisIdx = line.indexOf(oldstr, oldIdx)) >= 0) { for (int ix = oldIdx; ix < thisIdx; ix++) { sb.append(line.charAt(ix)); } sb.append(newstr); oldIdx = thisIdx + oldLen; } for (int ix = oldIdx; ix < lineLen; ix++) { sb.append(line.charAt(ix)); } } return sb.toString(); }
public static String replaceStringOld(String line, String oldstr, String newstr) { if (oldstr.compareTo(newstr) == 0) { return line; } StringBuffer sb = null; if (oldstr.length() == newstr.length()) { sb = new StringBuffer(line); int lastIdx = line.indexOf(oldstr); if (lastIdx >= 0) { do { sb.replace(lastIdx, lastIdx + newstr.length(), newstr); } while ((lastIdx = line.indexOf(oldstr, lastIdx + 1)) >= 0); } } else { sb = new StringBuffer(); int oldStrIdx = 0; int lastIdx = line.indexOf(oldstr); if (lastIdx >= 0) { do { for (int ix = oldStrIdx; ix < lastIdx; ix++) { sb.append(line.charAt(ix)); } sb.append(newstr); oldStrIdx = lastIdx + oldstr.length(); } while ((lastIdx = line.indexOf(oldstr, lastIdx + 1)) >= 0); } for (int ix = oldStrIdx; ix < line.length(); ix++) { sb.append(line.charAt(ix)); } } return sb.toString(); }
public static String replaceString1(String line, String oldstr, String newstr) { int oldLen = oldstr.length(); int newLen = newstr.length(); if (oldLen == 0 || oldstr.equals(newstr)) { return line; } StringBuffer sb = new StringBuffer(line); int bufIdx = 0; int oldIdx = 0; int thisIdx; while ((thisIdx = line.indexOf(oldstr, oldIdx)) >= 0) { bufIdx += (thisIdx - oldIdx); sb.replace(bufIdx, bufIdx + oldLen, newstr); bufIdx += newLen; oldIdx = thisIdx + oldLen; } return sb.toString(); }