Java字符串替換函數replace、replaceFirst、replaceAll


 

一、replace(String old,String new)

功能:將字符串中的所有old子字符串替換成new字符串

示例

String s="Hollow world!";
        System.out.println(s);
        System.out.println(s.replace("o", "#"));
        /*
         * 結果:Hollow world!
         *     H#ll#w w#rld!
         */

二、replaceAll(String arg0, String arg1)

其中字符串表示arg0為正則表達式

功能

將字符串中符合正則表達式arg0的所有子字符串,替換成字符串arg1

示例

        String s="Hollow world!";
        System.out.println(s);
        /**
         * 正則表達式中.表示除換行符以外的任意字符
         * 所以s.replaceAll(".", "#")的意思是
         * 將所有字符替換成#
         */
        System.out.println(s.replaceAll(".", "#"));
        /*
         * 結果:Hollow world!
         *     #############
         */

 

三、replaceFisrst(String arg0, String arg1)

其中字符串表示arg0為正則表達式

功能

將字符串中符合正則表達式arg0的第一個子字符串,替換成字符串arg1

示例

String s="Hollow world!";
        System.out.println(s);
        /**
         * 正則表達式中.表示除換行符以外的任意字符
         * 所以s.replaceFirst(".", "#")的意思是
         * 將第一個字符替換成#
         */
        System.out.println(s.replaceFirst(".", "#"));
        /*
         * 結果:Hollow world!
         *     #ollow world!
         */

注意:這三個方法返回替換后的字符串,原字符串不發生變化


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM