ฟังก์ชันใดที่สามารถแทนที่สตริงด้วยสตริงอื่นได้
ตัวอย่าง # 1: จะแทนที่"HelloBrother"
ด้วย"Brother"
อะไร?
ตัวอย่าง # 2: จะแทนที่"JAVAISBEST"
ด้วย"BEST"
อะไร?
ฟังก์ชันใดที่สามารถแทนที่สตริงด้วยสตริงอื่นได้
ตัวอย่าง # 1: จะแทนที่"HelloBrother"
ด้วย"Brother"
อะไร?
ตัวอย่าง # 2: จะแทนที่"JAVAISBEST"
ด้วย"BEST"
อะไร?
คำตอบ:
replace
วิธีคือสิ่งที่คุณกำลังมองหา
ตัวอย่างเช่น:
String replacedString = someString.replace("HelloBrother", "Brother");
String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");
System.out.println(r);
นี่จะเป็นการพิมพ์ว่า "Brother How are you!"
มีความเป็นไปได้ที่จะไม่ใช้ตัวแปรเสริม
String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);
การแทนที่สตริงหนึ่งด้วยอีกสตริงสามารถทำได้ในวิธีการด้านล่าง
วิธีที่ 1: การใช้ StringreplaceAll
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);
วิธีที่ 2 : การใช้Pattern.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);
วิธีที่ 3 : ใช้Apache Commons
ตามที่กำหนดไว้ในลิงค์ด้านล่าง:
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);
ข้อเสนอแนะอื่นสมมติว่าคุณมีคำเดียวกันสองคำใน String
String s1 = "who is my brother, who is your brother"; // I don't mind the meaning of the sentence.
แทนที่ฟังก์ชันจะเปลี่ยนทุกสตริงที่กำหนดในพารามิเตอร์แรกเป็นพารามิเตอร์ที่สอง
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
และคุณยังสามารถใช้วิธีการ replaceAll สำหรับผลลัพธ์เดียวกัน
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
หากคุณต้องการเปลี่ยนเฉพาะสตริงแรกซึ่งอยู่ในตำแหน่งก่อนหน้านี้
System.out.println(s1.replaceFirst("brother", "sister")); // whos is my sister, who is your brother.