论坛首页 Java企业应用论坛

使用substring()方法完成字符串替换.

浏览 2120 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (2) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-11-07   最后修改:2008-11-07

/*

利用substring()方法可以截取字符串,它有两种形式

String substring(int startIndex)

String substring(int startIndex, int endIndex)

*/

//Substring replacement.
public class StringReplace{
 public static void main(String[] args)
 {
  String org      = "This is a test. This is, too.";
  String search = "is";
  String sub     = "was";
  String result  = "";
  int i;
  do{ // replace all matching substrngs
   System.out.println(org);
   i = org.indexOf(search);
   if(i !=-1){
    result = org.substring(0,i);
    result = result + sub;
    result = result + org.substring(i + search.length());
    org = result;
   }
  }while(i != -1);
 }
}

 

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics