在JDK1.4中使用replace(CharSequence target, CharSequence replacement)

在JDK1.4中使用replace(CharSequence target, CharSequence replacement)

 

JDK1.5中

 Stringreplace(CharSequence target,CharSequence replacement)
          使用指定的字面值替换序列替换此字符串匹配字面值目标序列的每个子字符串

 

而JDK1.4无此方法,只有:

 StringreplaceAll(String regex,String replacement)
          Replaces each substring of this string that matches the given regular expression with the given replacement.

 

查看JDK1.5的代码中replace(CharSequence target,CharSequence replacement) 的实现方式

  1.     public String replace(CharSequence target, CharSequence replacement) {
  2.         return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
  3.             this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
  4.     }

其中Pattern.LITERAL在JD1.4中未实现,且涉及Pattern中的多处代码,不能直接替换。后来查询资料,发现在JDK1.5中存在两个方法:

static Stringquote(String s)
          返回指定 String 的字面值模式 String

 以及:

static String

quoteReplacement(String s)
返回指定 String 的字面值替换 String

 

但因为对正则表达式理解不足,均未成功(知道的兄弟可以告诉一声:));且Pattern中的static String quote(String s)结果出来后还需要调用Pattern中的此方法private void RemoveQEQuoting()进行还原

最终考虑自己写一个,但是检查发现在apache commons-lang中的StringUtils已经实现此功能:

static Stringreplace(String text, String searchString, String replacement)
Replaces all occurrences of a String within another String.

代码如下:

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    public static String replace(String text, String searchString, String replacement, int max) {
        if (isEmpty(text) || isEmpty(searchString) || replacement == null) {
            return text;
        }
        int start = 0;
        int end = text.indexOf(searchString, start);
        if (end == -1) {
            return text;
        }
        int replLength = searchString.length();
        int increase = replacement.length() - replLength;
        increase = (increase < 0 ? 0 : increase);
        increase *= 16;//此处没理解,为什么还要扩大StringBuffer
        StringBuffer buf = new StringBuffer(text.length() + increase);
        while (end != -1) {
            buf.append(text.substring(start, end)).append(replacement);
            start = end + replLength;
            end = text.indexOf(searchString, 2);
        }
        buf.append(text.substring(start));
        return buf.toString();
    }


 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值