Réponses:
String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");
System.out.println(r);
Cela imprimerait "Brother How are you!"
Il est possible de ne pas utiliser de variables supplémentaires
String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);
Le remplacement d'une chaîne par une autre peut être effectué dans les méthodes ci-dessous
Méthode 1: utilisation de la chaînereplaceAll
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);
Méthode 2 : utilisationPattern.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);
Méthode 3 : Utilisation Apache Commonstelle que définie dans le lien ci-dessous:
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);
Une autre suggestion, disons que vous avez deux mêmes mots dans la chaîne
String s1 = "who is my brother, who is your brother"; // I don't mind the meaning of the sentence.
remplacer la fonction changera chaque chaîne est donnée dans le premier paramètre au deuxième paramètre
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
et vous pouvez également utiliser la méthode replaceAll pour le même résultat
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
si vous souhaitez modifier uniquement la première chaîne positionnée plus tôt,
System.out.println(s1.replaceFirst("brother", "sister")); // whos is my sister, who is your brother.