Java字符串替换(replace()、replaceFirst()、replaceAll())

1、replace()方法

    public static void main(String[] args){
        String str = "hello world, hello java";
        str = str.replace("h","H");
        System.out.println(str);
    }
//输出:Hello world, Hello java

2、replaceFirst()方法

public static void main(String[] args){
        String str = "hello world, hello java";
        str = str.replaceFirst("hello","Hi");
        System.out.println(str);
    }
//输出:Hi world, hello java

3、replaceAll()方法

public static void main(String[] args){
        String str = "hello world, hello java";
        str = str.replaceAll("hello","Hi");
        System.out.println(str);
    }
//输出:Hi world, Hi java

4、扩展:将字符串 time:[* TO ] 中第二个替换为 test

//将字符串 time:[* TO *] 中第二个*替换为 test
    public static void main(String[] args){
        String test = "time:[* TO *TO]";
        String result1 = test.replaceAll("(\\*)(.*?)(\\1)(.*?)", "$1$2test$4");
        System.out.println("原字符串:" + test);
        System.out.println("替换后:" + result1);
    }
//原字符串:time:[* TO *TO]
//替换后:time:[* TO testTO]
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,314评论 0 3
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 4,465评论 0 5
  • 字符串(String)是一系列的字符(char)。例如“Hello”是5个字符。字符串是一个不可变的对象,也就是说...
    chonglingliu阅读 1,109评论 0 0
  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 5,819评论 0 10
  • Java 语言支持的类型分为两类:基本类型和引用类型。整型(byte 1, short 2, int 4, lon...
    xiaogmail阅读 1,369评论 0 10