首页 > 代码库 > java字符串替换函数高效实现
java字符串替换函数高效实现
1 public static String removeStr(String src, String str) { 2 if (src =http://www.mamicode.com/= null || str == null) return src; 3 int idx = src.indexOf(str); 4 if (idx == -1) return src; 5 int pst = 0; 6 char[] cs = src.toCharArray(); 7 char[] rs = new char[src.length() - str.length()]; 8 for (int i = 0; i < cs.length; i ++) { 9 if (i >= idx && i < idx + str.length()) continue;10 rs[pst] = cs[i];11 pst ++;12 }13 return new String(rs);14 }15 public static String replaceStr(String src, String target, String replacement) {16 if (src =http://www.mamicode.com/= null || target == null || replacement == null) return src;17 int idx = src.indexOf(target);18 if (idx == -1) return src;19 int pst = 0;20 char[] cs = src.toCharArray();21 char[] rs = new char[src.length() - target.length() + replacement.length()];22 for (int i = 0; i < cs.length; i ++) {23 if (i == idx) {24 for (char c : replacement.toCharArray()) {25 rs[pst] = c;26 pst ++;27 }28 continue;29 }30 if (i > idx && i < idx + target.length()) continue;31 rs[pst] = cs[i];32 pst ++;33 }34 return new String(rs);35 }36 /**37 * 38 * @param src39 * @param target40 * @param replacement41 * @return42 */43 public static String replaceAllStr(String src, String target, String replacement) {44 if (src =http://www.mamicode.com/= null || target == null || replacement == null) return src;45 int idx = src.indexOf(target);46 if (idx == -1) return src;47 int pst = 0;48 char[] cs = src.toCharArray();49 char[] rs = new char[src.length() - target.length() + replacement.length()];50 for (int i = 0; i < cs.length; i ++) {51 if (i == idx) {52 for (char c : replacement.toCharArray()) {53 rs[pst] = c;54 pst ++;55 }56 continue;57 }58 if (i > idx && i < idx + target.length()) continue;59 rs[pst] = cs[i];60 pst ++;61 }62 return replaceAllStr(new String(rs), target, replacement);63 }
java字符串替换函数高效实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。