zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    单片机4*4按键数码管显示0-9
    netbeans设置语言
    单片机中断的应用
    Linux 命令总结
    vc6.0快捷键大全
    怎么使PUTTY一直连接
    mysql alter 效率
    treeview
    Gitbook
    linux 进程监控软件 supervisor
  • 原文地址:https://www.cnblogs.com/wq920/p/5846910.html
Copyright © 2011-2022 走看看