/** * Given a string, replace all occurraces of 'newStr' with 'oldStr'. * * @param originalStr the string to modify. * @param oldStr the string to replace. * @param newStr the string to insert in place of the old string. */ public static String replaceText(String originalStr, String oldStr, String newStr) { if (oldStr == null || newStr == null || oldStr.equals(newStr)) { return originalStr; } StringBuffer result = new StringBuffer(originalStr); int startIndex = 0; while ((startIndex = result.indexOf(oldStr, startIndex)) != -1) { result = result.replace(startIndex, startIndex + oldStr.length(), newStr); startIndex += newStr.length(); } return result.toString(); }
/** * Given a string, replace all tabs with the appropriate number of spaces. * * @param tabLength the length of each tab. * @param s the String to scan. */ public static void replaceTabs(int tabLength, StringBuffer s) { int index, col; StringBuffer whitespace; while ((index = s.indexOf("\t")) != -1) { whitespace = new StringBuffer(); col = index; do { whitespace.append(" "); col++; } while ((col % tabLength) != 0); s.replace(index, index + 1, whitespace.toString()); } }