164 votes

Comment supprimer un caractère unique d'une chaîne de caractères

Pour accéder aux caractères individuels d'une chaîne en Java, nous avons String.charAt(2) . Existe-t-il une fonction intégrée pour supprimer un caractère individuel d'une chaîne de caractères en java ?

Quelque chose comme ça :

if(String.charAt(1) == String.charAt(2){
   //I want to remove the individual character at index 2. 
}

0voto

public String missingChar(String str, int n) {
  String front = str.substring(0, n);

// Start this substring at n+1 to omit the char.
// Can also be shortened to just str.substring(n+1)
// which goes through the end of the string.

String back = str.substring(n+1, str.length());
  return front + back;
}

0voto

fabiolimace Points 51

Je viens d'implémenter cette classe utilitaire qui supprime un caractère ou un groupe de caractères d'une chaîne de caractères. . Je pense qu'il est rapide car il n'utilise pas de Regexp. J'espère que cela aidera quelqu'un !

package your.package.name;

/**
 * Utility class that removes chars from a String.
 * 
 */
public class RemoveChars {

    public static String remove(String string, String remove) {
        return new String(remove(string.toCharArray(), remove.toCharArray()));
    }

    public static char[] remove(final char[] chars, char[] remove) {

        int count = 0;
        char[] buffer = new char[chars.length];

        for (int i = 0; i < chars.length; i++) {

            boolean include = true;
            for (int j = 0; j < remove.length; j++) {
                if ((chars[i] == remove[j])) {
                    include = false;
                    break;
                }
            }

            if (include) {
                buffer[count++] = chars[i];
            }
        }

        char[] output = new char[count];
        System.arraycopy(buffer, 0, output, 0, count);

        return output;
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
        String remove = "AEIOU";

        System.out.println();
        System.out.println("Remove AEIOU: " + string);
        System.out.println("Result:       " + RemoveChars.remove(string, remove));
    }
}

Voici le résultat :

Remove AEIOU: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Result:       TH QCK BRWN FX JMPS VR TH LZY DG

-2voto

Lekov Points 7

Par exemple, si vous voulez calculer combien de "a" il y a dans la chaîne, vous pouvez le faire comme suit :

if (string.contains("a"))
{
    numberOf_a++;
    string = string.replaceFirst("a", "");
}

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X