Câu trả lời:
Hãy thử cách này: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29
String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");
System.out.println(r);
Điều này sẽ in ra "Anh khỏe không!"
Có khả năng không sử dụng các biến phụ
String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);
Thay thế một chuỗi bằng chuỗi khác có thể được thực hiện trong các phương pháp dưới đây
Phương pháp 1: Sử dụng chuỗireplaceAll
String myInput = "HelloBrother";
String myOutput = myInput.replaceAll("HelloBrother", "Brother"); // Replace hellobrother with brother
---OR---
String myOutput = myInput.replaceAll("Hello", ""); // Replace hello with empty
System.out.println("My Output is : " +myOutput);
Phương pháp 2 : Sử dụngPattern.compile
import java.util.regex.Pattern;
String myInput = "JAVAISBEST";
String myOutputWithRegEX = Pattern.compile("JAVAISBEST").matcher(myInput).replaceAll("BEST");
---OR -----
String myOutputWithRegEX = Pattern.compile("JAVAIS").matcher(myInput).replaceAll("");
System.out.println("My Output is : " +myOutputWithRegEX);
Phương pháp 3 : Sử dụng Apache Commonsnhư được định nghĩa trong liên kết dưới đây:
http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)
String s1 = "HelloSuresh";
String m = s1.replace("Hello","");
System.out.println(m);
Một gợi ý khác, Giả sử bạn có hai từ giống nhau trong Chuỗi
String s1 = "who is my brother, who is your brother"; // I don't mind the meaning of the sentence.
hàm thay thế sẽ thay đổi mọi chuỗi được cung cấp trong tham số đầu tiên thành tham số thứ hai
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
và bạn cũng có thể sử dụng phương thức ReplaceAll cho cùng một kết quả
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
nếu bạn chỉ muốn thay đổi chuỗi đầu tiên được định vị trước đó,
System.out.println(s1.replaceFirst("brother", "sister")); // whos is my sister, who is your brother.