日期:2014-05-20 浏览次数:20703 次
public class Test { public static void main(String[] args) { String str = "123aa123aaa123bbb123ccc123ddd123aa123"; System.out.println(str); System.out.println(replace(str, "123", "***")); } public static String replace(String str, String old, String replacement) { StringBuffer sb = new StringBuffer(); int index = str.indexOf(old); if(index < 0) { return str; } int start = 0; int len = old.length(); do { sb.append(str.substring(start, index)) .append(replacement); start = index + len; index = str.indexOf(old, start); } while (index >= 0); sb.append(str.substring(start)); return sb.toString(); } }