Nội dung chính
Phương thức replaceAll trong Java String
Phương thức replaceAll() trả về một chuỗi thay thế tất cả các chuỗi ký tự phù hợp với regex.
Phương thức:
public String replaceAll(String regex, String replacement)
Ví dụ 1:
public class ReplaceAllExample1 { public static void main(String args[]) { String s1 = "kienthuclaptrinh is a very good website"; String replaceString = s1.replaceAll("t", "j"); //thay the "a" thanh "e" System.out.println(replaceString); } }
Output:
viejjujs is a very good websije
Ví dụ 1:
public class ReplaceAllExample1 { public static void main(String args[]) { String s1 = "kienthuclaptrinh is a very good website"; String replaceString = s1.replaceAll("t", "j"); //thay the "a" thanh "e" System.out.println(replaceString); } }
Output:
viejjujs is a very good websije
Ví dụ 2:
public class ReplaceAllExample1 { public static void main(String args[]) { String s1 = "My name is Khan. My name is Bob. My name is Sonoo."; String replaceString = s1.replaceAll("is", "was"); // thay the tat ca cac chuoi "is" thanh "was" System.out.println(replaceString); } }
Output:
My name was Khan. My name was Bob. My name was Sonoo.
Ví dụ 3:
public class ReplaceAllExample1 { public static void main(String args[]) { String s1 = "My name is Khan. My name is Bob. My name is Sonoo."; String replaceString = s1.replaceAll("\\s", "-"); // thay the khoang trang thanh "-" System.out.println(replaceString); } }
Output:
My-name-is-Khan.-My-name-is-Bob.-My-name-is-Sonoo