java字符串替换函数高效实现

 1 public static String removeStr(String src, String str) {
 2         if (src == 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 == 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 src
39      * @param target
40      * @param replacement
41      * @return
42      */
43     public static String replaceAllStr(String src, String target, String replacement) {
44         if (src == 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     }

 

posted @ 2016-09-06 19:08  wq920  阅读(7643)  评论(1编辑  收藏  举报