Java String – Phương thức replaceAll trong Java String

Java String

– Phương thức replaceAll trong Java String

Bài trước

Bài sau

Phương thức replaceAll trong Java String

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) {
		// TODO Auto-generated method stub
		String s1 = "hiepsiit.com is a very good website";
        String replaceString = s1.replaceAll("t", "j"); //thay the "a" thanh "e"  
        System.out.println(replaceString);
	}

}

Kết quả:

Ví dụ 2:

public class ReplaceAllExample2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s1 = "My name is HocLai. \nMy name is NoMon. \nMy name is TinChi.";
        String replaceString = s1.replaceAll("is", "was"); // thay the tat ca cac chuoi "is" thanh "was"
        System.out.println(replaceString);
	}

}

Kết quả:

Ví dụ 3:

public class ReplaceAllExample3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s1 = "My name is HocLai. \nMy name is NoMon. \nMy name is TinChi.";
        String replaceString = s1.replaceAll("\\s", "-"); // thay the khoang trang thanh "-"
        System.out.println(replaceString);
	}

}

Kết quả:

Bài trước

Bài sau