java replace字元替換函數的使用方法

來源:互聯網
上載者:User

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;
 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.