Java中的字符串替换

在Java中,String 类提供了 3 种字符串替换方法,分别是 replace()、replaceFirst() 和 replaceAll(),下面我们就来详细看一下三种的用法!

    下面这套Java300集视频专门为零基础而制,适合准备入行Java开发的零基础,视频中穿插多个实战项目。每一个知识点都讲解的通俗易懂,由浅入深。不仅适用于零基础的初学者,有经验的程序员也可做巩固学习。

replace() 方法

        replace() 方法用于将目标字符串中的指定字符(串)替换成新的字符(串),其语法格式如下:

字符串.replace(String oldChar, String newChar)

        其中,oldChar 表示被替换的字符串;newChar 表示用于替换的字符串。replace() 方法会将字符串中所有 oldChar 替换成 newChar。

例 1:

        创建一个字符串,对它使用 replace() 方法进行字符串替换并输出结果。代码如下:

public static void main(String[] args) {

    String words = "hello java,hello php";

    System.out.println("原始字符串是'"+words+"'");

    System.out.println("replace(\"l\",\"D\")结果:"+words.replace("l","D"));

    System.out.println("replace(\"hello\",\"你好\")结果:"+words.replace("hello","你好 "));

    words = "hr's dog";

    System.out.println("原始字符串是'"+words+"'");

    System.out.println("replace(\"r's\",\"is\")结果:"+words.replace("r's","is"));

}

        输出结果如下所示:

原始字符串是'hello java,hello php'

replace("l","D")结果:heDDo java,heDDo php

replace("hello","你好")结果:你好 java,你好 php

原始字符串是'hr's dog'

replace("r's","is")结果:his dog

replaceFirst() 方法

        replaceFirst() 方法用于将目标字符串中匹配某正则表达式的第一个子字符串替换成新的字符串,其语法形式如下:

字符串.replaceFirst(String regex, String replacement)

        其中,regex 表示正则表达式;replacement 表示用于替换的字符串。例如:

String words = "hello java,hello php";

String newStr = words.replaceFirst("hello","你好 ");

System.out.println(newStr);    // 输出:你好 java,hello php

replaceAll() 方法

        replaceAll() 方法用于将目标字符串中匹配某正则表达式的所有子字符串替换成新的字符串,其语法形式如下:

字符串.replaceAll(String regex, String replacement)

其中,regex 表示正则表达式,replacement 表示用于替换的字符串。例如:

String words = "hello java,hello php";

String newStr = words.replaceAll("hello","你好 ");

System.out.println(newStr);    // 输出:你好 java,你好 php

        Java字符串的替换主要就是这样了,多多练习。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值