Java中String字符串替换3种方法详解

时间:2025-02-15 20:41:27

()方法

replace() 方法用于将目标字符串中的指定字符(串)替换成新的字符(串)
字符串.replace(String oldChar, String newChar)

public class Test1 {
    public static void main(String[] args)  {
        String a = "1-1-1-1";
        String result = a.replace("-","");
        System.out.println(result);
    }
}

1111

()方法

replaceFirst() 方法用于将目标字符串中匹配某正则表达式的第一个子字符串替换成新的字符串
字符串.replaceFirst(String regex, String replacement)

public class Test1 {
    public static void main(String[] args)  {
        String a = "1-1-1-1";
        String result = a.replaceFirst("1","0");
        System.out.println(result);
    }
}
0-1-1-1

()方法

replaceAll() 方法用于将目标字符串中匹配某正则表达式的所有子字符串替换成新的字符串
字符串.replaceAll(String regex, String replacement)

public class Test1 {
    public static void main(String[] args)  {
        String a = "1-1-1-1";
        String result = a.replaceAll("1","0");
        System.out.println(result);
    }
}
0-0-0-0