java字符串替换函数⾼效实现 1public static String removeStr(String src, String str) {
2if (src == null || str == null) return src;
3int idx = src.indexOf(str);
4if (idx == -1) return src;
5int pst = 0;
6char[] cs = CharArray();
7char[] rs = new char[src.length() - str.length()];
8for (int i = 0; i < cs.length; i ++) {
9if (i >= idx && i < idx + str.length()) continue;
10 rs[pst] = cs[i];
11 pst ++;
12 }
13return new String(rs);
14 }
15public static String replaceStr(String src, String target, String replacement) {
16if (src == null || target == null || replacement == null) return src;
17int idx = src.indexOf(target);
18if (idx == -1) return src;
19int pst = 0;
20char[] cs = CharArray();
21char[] rs = new char[src.length() - target.length() + replacement.length()];
22for (int i = 0; i < cs.length; i ++) {
23if (i == idx) {
24for (char c : CharArray()) {
25 rs[pst] = c;
26 pst ++;
27 }
28continue;
29 }
30if (i > idx && i < idx + target.length()) continue;
31 rs[pst] = cs[i];
32 pst ++;
33 }
34return new String(rs);
35 }
36/**
37 *
38 * @param src
39 * @param target
40 * @param replacement
41 * @return
42*/
43public static String replaceAllStr(String src, String target, String replacement) {
44if (src == null || target == null || replacement == null) return src;
45int idx = src.indexOf(target);
46if (idx == -1) return src;
47int pst = 0;
48char[] cs = CharArray();
49char[] rs = new char[src.length() - target.length() + replacement.length()];
50for (int i = 0; i < cs.length; i ++) {
51if (i == idx) {
52for (char c : CharArray()) {
53 rs[pst] = c;
54 pst ++;
java replace方法55 }
56continue;
57 }
58if (i > idx && i < idx + target.length()) continue;
59 rs[pst] = cs[i];
60 pst ++;
61 }
62return replaceAllStr(new String(rs), target, replacement);
63 }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论