java字符串替换字符串实例,对replace方法的重写

package com.citycollege.stw;

public class testreplace {

 
 
 public static final String replace( String line, String oldString, String newString )
    {
        if (line == null)
   {
    return null;
            }
        int i=0;
        if ( ( i=line.indexOf( oldString, i ) ) >= 0 )
   {
    char [] line2 = line.toCharArray(); //字符串放入数组
    char [] newString2 = newString.toCharArray(); //要替换的字符串
    int oLength = oldString.length();  //被替换的字符串的长度
    StringBuffer buf = new StringBuffer(line2.length);
    buf.append(line2, 0, i).append(newString2);
    i += oLength;
    int j = i;
    while( ( i=line.indexOf( oldString, i ) ) > 0 )
     {
      buf.append(line2, j, i-j).append(newString2);
      i += oLength;
      j = i;
                    }
    buf.append(line2, j, line2.length - j);
    return buf.toString();
   }
   return line;
    }     

 

 
 
 
 
  public static void main(String args[]){
         String s="I OK OK best OK" +
           "She OK OK BESTU OK";
         String s1=replace(s,"OK","hello");
          System.out.println(s1);
         
         
          String s2="I OK OK best OK";
          String temp="hello";
       String s3=s2.replace("0K", temp);
   
           System.out.println(s3);
          
         
         
         
         
         
         
         
         
  }

 
 
 
 
 
 
 
 
 
}

阅读更多
文章标签: java string null class
个人分类: s2sh框架
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭