¿Cómo puedo eliminar una subcadena de una cadena dada?


¿Hay una manera fácil de eliminar subcadenas de una cadena dada en Java ?

Ejemplo: "Hello World!", removing " o "- > " Hell Wrld!"

 126
Author: stacker, 2011-10-15

8 answers

Usted podría utilizar fácilmente String.replace():

String helloWorld = "Hello World!";
String hellWrld = helloWorld.replace("o","");
 264
Author: Justin Niessner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-15 03:08:27

Puedes usar StringBuffer

StringBuffer text = new StringBuffer("Hello World");
text.replace( StartIndex ,EndIndex ,String);
 7
Author: Magdi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-30 12:57:33
replace('regex', 'replacement');
replaceAll('regex', 'replacement');

En su ejemplo,

String hi = "Hello World!"
String no_o = hi.replaceAll("o", "");
 6
Author: Cory Kendall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-15 02:35:25

Echa un vistazo Apache StringUtils :

  • static String replace(String text, String searchString, String replacement) Reemplaza todas las ocurrencias de una cadena dentro de otra Cadena.
  • static String replace(String text, String searchString, String replacement, int max) Reemplaza una cadena con otra Cadena dentro de una cadena más grande, para los primeros valores máximos de la cadena de búsqueda.
  • static String replaceChars(String str, char searchChar, char replaceChar) Reemplaza todas las ocurrencias de un carácter en una cadena con otro.
  • static String replaceChars(String str, String searchChars, String replaceChars) Reemplaza varios caracteres en una cadena de una sola vez.
  • static String replaceEach(String text, String[] searchList, String[] replacementList) Reemplaza todas las ocurrencias de cadenas dentro otra Cuerda.
  • static String replaceEachRepeatedly(String text, String[] searchList, String[] replacementList) Reemplaza todas las ocurrencias de Cadenas dentro de otra cadena.
  • static String replaceOnce(String text, String searchString, String replacement) Reemplaza una cadena con otra Cadena dentro de una cuerda más grande, una vez.
  • static String replacePattern(String source, String regex, String replacement) Reemplaza cada subcadena de la cadena de origen que coincide la expresión regular dada con el reemplazo dado usando patrón.Opción DOTALL.
 5
Author: DwB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-14 18:20:57

Debe mirar StringBuilder/StringBuffer que le permite eliminar, insertar, reemplazar caracteres en el desplazamiento especificado.

 3
Author: adatapost,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-15 02:49:36

También puedes usar de guayaba CharMatcher.Función removeFrom .

Ejemplo:

 String s = CharMatcher.is('a').removeFrom("bazaar");
 2
Author: Emil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-15 03:49:30

Esto funciona bien para mí.

String hi = "Hello World!"
String no_o = hi.replaceAll("o", "");

O puede usar

String no_o = hi.replace("o", "");
 2
Author: Tariqul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-24 04:32:33
  private static void replaceChar() {
    String str = "hello world";
    final String[] res = Arrays.stream(str.split(""))
            .filter(s -> !s.equalsIgnoreCase("o"))
            .toArray(String[]::new);
    System.out.println(String.join("", res));
}

En caso de que tenga alguna lógica complicada para filtrar el carácter, solo otra forma en lugar de reemplazar.

 0
Author: Sean,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-08 02:07:13