2011-03-07 16 views
69

Quale funzione può sostituire una stringa con un'altra stringa?sostituire String con un altro in java

Esempio n. 1: Cosa sostituirà "HelloBrother" con "Brother"?

Esempio n. 2: Cosa sostituirà "JAVAISBEST" con "BEST"?

+2

Quindi vuoi solo l'ultima parola? – SNR

+1

Di cosa hai bisogno esattamente? – RAY

risposta

109

Il metodo replace è quello che stai cercando.

Ad esempio:

String replacedString = someString.replace("HelloBrother", "Brother"); 
5
 String s1 = "HelloSuresh"; 
    String m = s1.replace("Hello",""); 
    System.out.println(m); 
5

Sostituzione di una stringa con un'altra può essere realizzata in metodi indicati

Metodo 1: Uso String 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);  

Metodo 2: Usando 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);   

Metodo 3: Utilizzo Apache Commons come definito nel link qui sotto:

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) 

REFERENCE

4

v'è la possibilità di non usare variabili aggiuntive

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

Non è certo una nuova risposta, ma un miglioramento della risposta di @ DeadProgrammer. –

Problemi correlati