字符串后n位用*号代替各方法效率评测,字符串,/** * */pac
分享于 点击 43429 次 点评:167
字符串后n位用*号代替各方法效率评测,字符串,/** * */pac
/** * */package com.comm;public class Comm{ /** * 第一种方法,把字符串的后n位用“*”号代替 * * @param str * 要代替的字符串 * @param n * 代替的位数 * @return */ public static String replaceSubString(String str, int n) { String sub = ""; sub = str.substring(0, str.length() - n); StringBuffer sb = new StringBuffer(); for (int i = 0; i < n; i++) { sb = sb.append("*"); } sub += sb.toString(); return sub; } /** * 第二种方法 * * @param org * @param n * @return */ public static String replaceString(String org, int n) { char[] cs = org.toCharArray(); int len = org.length(); for (int i = 0; i < n; i++) { cs[len - i - 1] = '*'; } return String.valueOf(cs); } /** * 第三种方法 * * @param org * @param n * @return */ public static String replaceString3(String org, int n) { StringBuffer sb = new StringBuffer(org.substring(0, org.length() - n)); for (int i = 0; i < n; i++) { sb.append('*'); } return sb.toString(); } /** * @param args */ public static void main(String[] args) { String str = "13560732344ssssssssssssssssssfffffffffff"; int n = 10; int times = 1000000; System.out.println("第一种结果:" + replaceSubString(str, n)); System.out.println("第二种结果:" + replaceString(str, n)); System.out.println("第三种结果:" + replaceString3(str, n)); long tm1 = System.currentTimeMillis(); for (int i = 0; i < times; i++) { replaceSubString(str, n); } long tm2 = System.currentTimeMillis(); for (int i = 0; i < times; i++) { replaceString(str, n); } long tm3 = System.currentTimeMillis(); for (int i = 0; i < times; i++) { replaceString3(str, n); } long tm4 = System.currentTimeMillis(); System.out.println("第一种方法用时:" + (tm2 - tm1)); System.out.println("第二种方法用时:" + (tm3 - tm2)); System.out.println("第三种方法用时:" + (tm4 - tm3)); }}//该片段来自于http://byrx.net
用户点评