Jawaban:
String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");
System.out.println(r);
Ini akan mencetak "Saudaraku, Bagaimana kabarmu!"
Ada kemungkinan untuk tidak menggunakan variabel tambahan
String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);
Mengganti satu string dengan yang lain dapat dilakukan dengan metode di bawah ini
Metode 1: Menggunakan 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);
Metode 2 : MenggunakanPattern.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);
Metode 3 : Menggunakan Apache Commonsseperti yang ditentukan pada tautan di bawah ini:
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);
Saran lain, Katakanlah Anda memiliki dua kata yang sama dalam String
String s1 = "who is my brother, who is your brother"; // I don't mind the meaning of the sentence.
fungsi replace akan mengubah setiap string yang diberikan di parameter pertama ke parameter kedua
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
dan Anda juga dapat menggunakan metode replaceAll untuk hasil yang sama
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
jika Anda ingin mengubah hanya string pertama yang diposisikan sebelumnya,
System.out.println(s1.replaceFirst("brother", "sister")); // whos is my sister, who is your brother.