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!
             */

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

  • 相关阅读:
    DirectX9:基础篇 第五章 绘制流水线
    他山之石:可以攻玉
    C89:论内存分配问题
    C89:关键字
    MFC:开头篇 介绍
    DirectX9:先导篇 数学基础
    模仿轮播图效果
    text选中后displa出label内容
    ASP.NET页面之间传递值的几种方式
    jquery-delay(),queue()
  • 原文地址:https://www.cnblogs.com/wei-jing/p/10554918.html
Copyright © 2011-2022 走看看