Java replace()和replaceAll()的区别

本文介绍了Java中字符串处理的两个关键方法:replace和replaceAll。replace方法用于简单的字符串替换,例如将特定字符替换为另一个字符,而replaceAll方法支持使用正则表达式进行替换,如将所有空格替换为其他字符或查找并替换邮箱地址中的特定模式。
摘要由CSDN通过智能技术生成

replace()和replaceAll()说明

java中replace方法主要用于替换字符串,他有两个参数
参数1:替换前的字符串
参数2:想要替换的字符串

replace基本用法

//需求:将字符串g改为d
public class test {
    public static void main(String[] args) {
      String str=" a   b   c    g  u   h  k    j ";
      str=str.replace("g","d");
      System.out.println(str); 
      //-->a   b   c    d  u   h  k    j 
    }
}

replace多层嵌套用法

//需求:将a替换为壹、b>贰、c>叁、g>肆、u>伍
public class test {
    public static void main(String[] args) {
      String str=" a   b   c    g  u   h  k    j ";
      str=str
       .replace("a","壹")
       .replace("b","贰")
       .replace("c","叁")
       .replace("g","肆")
       .replace("u","伍");
      System.out.println(str);
      //-->壹   贰   叁    肆  伍   h  k    j
    }
}

replace与replaceAll的区别

replaceAll的用法replace基本相同,不同的是replaceAll的第一个参数可以用正则表达(regex)

replaceAll使用说明
参数1:替换前的字符串 可以用正则表达
参数2:想要替换的字符串

//需求替换字符串内所有大小空格为一个、连接
public class test {
    public static void main(String[] args) {
        String str="a b     c   g u     h   k     j";
        //正则匹配所有空格,替换为、
        str=str.replaceAll(" +","、");
        System.out.println(str);
      //-->a、b、c、g、u、h、k、j
    }
}

实例2:更改邮箱地址

//需求:将邮箱中任意@xxxx. 字符串改为@gmail
public class test2 {
    public static void main(String[] args) {
        String str="203455278@qq.com";
        String postBox = str.replaceAll("@.+\.","@gmail.");
        
        System.out.println(postBox);
        //-->203455278@gmail.com
    }
}

希望当前文章对你的开发有所帮助~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值