zoukankan      html  css  js  c++  java
  • 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!
             */

    注意:这三个方法返回替换后的字符串,原字符串不发生变化

  • 相关阅读:
    Vue 从入门到进阶之路(十)
    Vue 从入门到进阶之路(九)
    MySQL 小记
    Vue 从入门到进阶之路(八)
    Vue 从入门到进阶之路(七)
    Vue 从入门到进阶之路(六)
    Vue 从入门到进阶之路(五)
    MongoDB 小记
    Vue 从入门到进阶之路(四)
    Vue 从入门到进阶之路(三)
  • 原文地址:https://www.cnblogs.com/wei-jing/p/10554918.html
Copyright © 2011-2022 走看看