一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

java replace字符替换函数的使用方法

时间:2011-05-13 编辑:简简单单 来源:一聚教程网

java replace字符替换函数的使用方法

replace(char oldChar, char newChar)

public class MainClass
{
   public static void main( String args[] )
   {
      String s1 = new String( "hello" );
      String s2 = new String( "GOODBYE" );
      String s3 = new String( "   spaces   " );

      System.out.printf( "s1 = %sns2 = %sns3 = %snn", s1, s2, s3 );

      // test method replace     
      System.out.printf("Replace 'l' with 'L' in s1: %snn", s1.replace( 'l', 'L' ) );


   } // end main
}

结果

s1 = hello
s2 = GOODBYE
s3 =    spaces  

Replace 'l' with 'L' in s1: heLLo


将空格换成 /

public class MainClass {

  public static void main(String[] arg) {
    String text = "To be or not to be, that is the question.";
    String newText = text.replace(' ', '/');     // Modify the string text
   
    System.out.println(newText);
  }

}

结果
To/be/or/not/to/be,/that/is/the/question.

有朋友自己写了一个replace函数

// 替换字符串函数
 // String strSource - 源字符串
 // String strFrom  - 要替换的子串
 // String strTo   - 替换为的字符串
 public static String replace(String strSource, String strFrom, String strTo)
 {
   // 如果要替换的子串为空,则直接返回源串
   if(strFrom == null || strFrom.equals(""))
     return strSource;
   String strDest = "";
   // 要替换的子串长度
   int intFromLen = strFrom.length();
   int intPos;
   // 循环替换字符串
   while((intPos = strSource.indexOf(strFrom)) != -1)
   {
     // 获取匹配字符串的左边子串
     strDest = strDest + strSource.substring(0,intPos);
     // 加上替换后的子串
     strDest = strDest + strTo;
     // 修改源串为匹配子串后的子串
     strSource = strSource.substring(intPos + intFromLen);
   }
   // 加上没有匹配的子串
   strDest = strDest + strSource;
   // 返回
   return strDest;
 }

热门栏目