แทนที่ String ด้วยอีกอันใน java


97

ฟังก์ชันใดที่สามารถแทนที่สตริงด้วยสตริงอื่นได้

ตัวอย่าง # 1: จะแทนที่"HelloBrother"ด้วย"Brother"อะไร?

ตัวอย่าง # 2: จะแทนที่"JAVAISBEST"ด้วย"BEST"อะไร?


2
คุณต้องการเพียงคำสุดท้าย?
SNR

คำตอบ:


147

replaceวิธีคือสิ่งที่คุณกำลังมองหา

ตัวอย่างเช่น:

String replacedString = someString.replace("HelloBrother", "Brother");

46

ลองสิ่งนี้: 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);

นี่จะเป็นการพิมพ์ว่า "Brother How are you!"


6
เกือบ -1 สำหรับการให้ลิงค์ไปยังสำเนาโบราณของ Javadocs
Stephen C

10

มีความเป็นไปได้ที่จะไม่ใช้ตัวแปรเสริม

String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);

1
ไม่ใช่คำตอบใหม่ แต่เป็นการปรับปรุงคำตอบของ @ DeadProgrammer
Karl Richter

นี่คือคำตอบที่มีอยู่โปรดลองใช้วิธีการอื่น @oleg sh
Lova Chittumuri

7

การแทนที่สตริงหนึ่งด้วยอีกสตริงสามารถทำได้ในวิธีการด้านล่าง

วิธีที่ 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)

การอ้างอิง



0

ข้อเสนอแนะอื่นสมมติว่าคุณมีคำเดียวกันสองคำใน 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.
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.