java replace()字元替換函數

來源:互聯網
上載者:User

public String replace(char oldChar, char newChar)
返回一個新的字串,它是通過用 newChar 替換此字串中出現的所有 oldChar 得到的。
 如果 oldChar 在此 String 對象表示的字元序列中沒有出現,則返回對此 String 對象的引用。
否則,建立一個新的 String 對象,它所表示的字元序列除了所有的 oldChar 都被替換為 newChar 之外,與此 String 對象表示的字元序列相同

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
}

對於特殊nr我們把它替換成br

public class Main {
  public static void main(String[] argv) {

    System.out.println("rn|r|n|nr".replaceAll("(rn|r|n|nr)", "<br>"));

  }
}
//<br>|<br>|<br>|<br><br>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.