利用StringBuffer来替换内容

 1 package com.test.java;
 2 
 3 public class StringBufferTest {
 4 
 5     public static void main(String[] args) {
 6         String s = "0123456|78987|6543210"; // 原始string
 7         String re = "78987";// 原始string中需要被替换的内容
 8         String s_re1 = "789-987";// 新内容1
 9         String s_re2 = "7890987";// 新内容2
10 
11         StringBuffer sb = new StringBuffer(s);// 构造一个StringBuffer
12         System.out.println("替换前:" + sb.toString());
13 
14         //使用replace方式替换
15         int l = re.length();// 获取re的长度
16         int p = sb.lastIndexOf(re); // 获取re在原始string中的起始位置
17         sb.replace(p, p + l, s_re1);// 开始替换
18         System.out.println("第一次替换后:" + sb.toString());
19 
20         // 用delete和insert方式替换
21         int length = s_re1.length();
22         int pIndex = sb.lastIndexOf(s_re1);
23         sb.delete(pIndex, pIndex + length);
24         System.out.println("删除内容后:" + sb.toString());
25         sb.insert(pIndex, s_re2);
26         System.out.println("插入内容后:" + sb.toString());
27     }
28 
29 }

result:

1 替换前:0123456|78987|6543210
2 第一次替换后:0123456|789-987|6543210
3 删除内容后:0123456||6543210
4 插入内容后:0123456|7890987|6543210
原文地址:https://www.cnblogs.com/moonpool/p/5710381.html