2011-03-07 22 views
69

Qué función puede reemplazar una cadena con otra cadena?reemplazar cadena con otra en Java

Ejemplo n. ° 1: ¿Qué reemplazará a "HelloBrother" con "Brother"?

Ejemplo # 2: ¿Qué reemplazará a "JAVAISBEST" con "BEST"?

+2

Así que quieres sólo la última palabra? – SNR

+1

¿Qué es exactamente lo que necesita? Casi – RAY

Respuesta

109

El método replace es lo que estás buscando.

Por ejemplo:

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

Sustitución de una cadena con otra se puede hacer en los métodos siguientes

Método 1: Utilizando serie 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étodo 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);   

Método 3: Usando Apache Commons como se define en el siguiente enlace:

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

Existe la posibilidad de no utilizar variables adicionales

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

No es una respuesta nueva, sino una mejora de la respuesta de @ DeadProgrammer. –

Cuestiones relacionadas