remplacer la chaîne par une autre en java
Quelle fonction peut remplacer une chaîne par une autre chaîne?
Exemple # 1: Qu'est-ce qui remplacera "HelloBrother"
par "Brother"
?
Exemple # 2: Qu'est-ce qui remplacera "JAVAISBEST"
par "BEST"
?
83
Author: Oliver Spryn, 2011-03-07
5 answers
Le replace
la méthode est ce que vous cherchez.
Par exemple:
String replacedString = someString.replace("HelloBrother", "Brother");
128
Author: pwc, 2015-09-25 07:40:20
Essayez ceci: http://download.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28char,%20char%29
String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");
System.out.println(r);
Cela imprimerait " Frère Comment allez-vous!"
36
Author: ProNeticas, 2018-06-11 16:48:35
Il est possible de ne pas utiliser de variables supplémentaires
String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);
8
Author: Oleg SH, 2017-05-10 14:28:03
Remplacer une chaîne par une autre peut être fait dans les méthodes ci-dessous
Méthode 1: En utilisant la chaîne replaceAll
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: À L'Aide De 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);
Méthode 3: En utilisant {[5] } comme défini 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)
6
Author: Nishanthi Grashia, 2017-05-23 11:55:01
String s1 = "HelloSuresh";
String m = s1.replace("Hello","");
System.out.println(m);
5
Author: Dead Programmer, 2011-03-07 05:55:45