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

Posted The-Most-Speial

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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     }

 

以上是关于java字符串替换函数高效实现的主要内容,如果未能解决你的问题,请参考以下文章

[Java]_[初级]_[使用正则高效替换字符串的多个占位符为多个值]

[Java]_[初级]_[使用正则高效替换字符串的多个占位符为多个值]

千字分析剑指 Offer 05. 替换空格

java string

java 为啥要实现 function?

VB编程,实现字符串替换功能