public String replace(String text, String oldStr, String newStr) { int oldLen = oldStr.length(); int k = 0; while (k + oldLen <= text.length()) {// 检测到字符串末尾 k = text.indexOf(oldStr, k);// 从k处查找oldStr,并返回位置 if (k == -1)// 若查不到,则跳出 return text; // 若有,则将其替换为newStr int i = k + oldLen; text = text.substring(0, k) + newStr + text.substring(i, text.length()); } return text; }