代码如下: import Java.util.regex.*; public class regex { public regex() { } public static String replaceByRegex (String input,String toChg,String chgTo) { StringBuffer sb = null; if (input==nullinput.length()==0) return input; if (toChg==nulltoChg.length()==0) return input; Pattern chagePattern = Pattern.compile(toChg); Matcher inputMatcher = chagePattern.matcher(input); sb = new StringBuffer(); while (inputMatcher.find()) { inputMatcher.appendReplacement(sb,chgTo); } inputMatcher.appendTail(sb); return sb.toString(); } public static String replaceByStringBuffer(String _old,String _str,String _new) { if (_old==null) {return null;} StringBuffer _temp=new StringBuffer(); int i=0; int j=0; while((j=_old.indexOf(_str,0))!=-1) { _temp.append(_old.substring(0,j)+_new); _old=_old.substring(j+_str.length()); } _temp.append( _old); return _temp.toString(); } public static String replaceByString(String _old,String _str,String _new) { if (_old==null) {return null;} String _temp=""; int i=0; int j=0; while((j=_old.indexOf(_str,0))!=-1) { _temp+=_old.substring(0,j)+_new; _old=_old.substring(j+_str.length()); } _temp+=_old; return _temp; } public static void main(String[] args) throws Throwable { String tmp = "the the ii bb ttisc hisadf. oeoflaksdjflkjeivnlaskdfjiieiah"; long t = System.currentTimeMillis(); for (int i=0;i<100000;i++,regex.replaceByStringBuffer(tmp,"i","WW")); System.out.println("replace it by string buffer :"+(System.currentTimeMillis()-t)); t = System.currentTimeMillis(); for (int i=0;i<100000;i++,regex.replaceByString(tmp,"i","WW")); System.out.println("replace it by string :"+(System.currentTimeMillis()-t)); t = System.currentTimeMillis(); for (int i=0;i<100000;i++,regex.replaceByRegex(tmp,"i","WW")); System.out.println("replace it by regex :"+(System.currentTimeMillis()-t)); } } 测试结果: replace it by string buffer :2443 replace it by string :3305 replace it by regex :4226 可见,
|