web-dev-qa-db-fra.com

Comment puis-je supprimer une sous-chaîne d'une chaîne donnée?

Existe-t-il un moyen simple de supprimer une sous-chaîne d'une chaîne donnée en Java? 

exemple: "Hello World!" , en supprimant "o" -> "Hell Wrld!"

140
Belgi

Vous pouvez facilement utiliser String.replace() :

String helloWorld = "Hello World!";
String hellWrld = helloWorld.replace("o","");
291
Justin Niessner

Vous pouvez utiliser StringBuffer 

StringBuffer text = new StringBuffer("Hello World");
text.replace( StartIndex ,EndIndex ,String);
8
Magdi
replace('regex', 'replacement');
replaceAll('regex', 'replacement');

Dans votre exemple

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

Découvrez Apache StringUtils :

  • static String replace(String text, String searchString, String replacement) Remplace toutes les occurrences d'une chaîne dans une autre Chaîne.
  • static String replace(String text, String searchString, String replacement, int max) Remplace une chaîne par une autre chaîne dans un String plus grand, pour les premières valeurs maximales de la chaîne de recherche.
  • static String replaceChars(String str, char searchChar, char replaceChar) Remplace toutes les occurrences d'un caractère dans une chaîne par un autre.
  • static String replaceChars(String str, String searchChars, String replaceChars) Remplace plusieurs caractères d'une chaîne en une fois.
  • static String replaceEach(String text, String[] searchList, String[] replacementList) Remplace toutes les occurrences de chaînes dans une autre chaîne.
  • static String replaceEachRepeatedly(String text, String[] searchList, String[] replacementList) Remplace toutes les occurrences de Chaînes dans une autre chaîne.
  • static String replaceOnce(String text, String searchString, String replacement) Remplace une chaîne par une autre chaîne dans un plus grand String, une fois.
  • static String replacePattern(String source, String regex, String replacement) Remplace chaque sous-chaîne de la chaîne source que correspond à l'expression régulière donnée avec le remplacement donné à l'aide de l'option Pattern.DOTALL.
5
DwB

Cela fonctionne bien pour moi.

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

ou vous pouvez utiliser 

String no_o = hi.replace("o", "");
3
Tariqul

Vous devriez avoir à regarder StringBuilder/StringBuffer qui vous permet de supprimer, insérer, remplacer les caractères à la spécification offset .

3
adatapost

Vous pouvez également utiliser guava'sCharMatcher.removeFrom function.

Exemple:

 String s = CharMatcher.is('a').removeFrom("Bazaar");
2
Emil
  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));
}

au cas où vous auriez une logique compliquée pour filtrer le caractère, utilisez une autre méthode au lieu de la remplacer.

0
Sean

Si vous connaissez les index de début et de fin, vous pouvez utiliser cette option.

string = string.substring(0, start_index) + string.substring(end_index, string.length());
0
Harsh

Voici l'implémentation pour supprimer toutes les sous-chaînes de la chaîne donnée

public static String deleteAll(String str, String pattern)
{
    for(int index = isSubstring(str, pattern); index != -1; index = isSubstring(str, pattern))
        str = deleteSubstring(str, pattern, index);

    return str;
}

public static String deleteSubstring(String str, String pattern, int index)
{
    int start_index = index;
    int end_index = start_index + pattern.length() - 1;
    int dest_index = 0;
    char[] result = new char[str.length()];


    for(int i = 0; i< str.length() - 1; i++)
        if(i < start_index || i > end_index)
            result[dest_index++] = str.charAt(i);

    return new String(result, 0, dest_index + 1);
}

L'implémentation de la méthode isSubstring () est ici

0
Pratik Patil

Vous pouvez également utiliser Substring pour remplacer par une chaîne existante:

var str = "abc awwwa";
var Index = str.indexOf('awwwa');
str = str.substring(0, Index);
0
replaceAll(String regex, String replacement)

La méthode ci-dessus aidera à obtenir la réponse.

String check = "Hello World";
check = check.replaceAll("o","");
0
OneSix