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. 
}

1voto

Pankaj Points 926

Utiliser la fonction replaceFirst de la classe String. Il existe de nombreuses variantes de la fonction replace que vous pouvez utiliser.

1voto

Farhan Syed Points 326

Si vous avez besoin d'un contrôle logique sur la suppression des caractères, utilisez ceci

String string = "sdsdsd";
char[] arr = string.toCharArray();
// Run loop or whatever you need
String ss = new String(arr);

Si vous n'avez pas besoin d'un tel contrôle, vous pouvez utiliser ce que Oscar ou Bhesh ont mentionné. Ils ont tout à fait raison.

1voto

user3636561 Points 1

Le moyen le plus simple de supprimer un caractère d'une chaîne de caractères.

String str="welcome";
str=str.replaceFirst(String.valueOf(str.charAt(2)),"");//'l' will replace with "" 
System.out.println(str);//output: wecome

1voto

SanA Points 119
public class RemoveCharFromString {
    public static void main(String[] args) {
        String output = remove("Hello", 'l');
        System.out.println(output);
    }

    private static String remove(String input, char c) {

        if (input == null || input.length() <= 1)
            return input;
        char[] inputArray = input.toCharArray();
        char[] outputArray = new char[inputArray.length];
        int outputArrayIndex = 0;
        for (int i = 0; i < inputArray.length; i++) {
            char p = inputArray[i];
            if (p != c) {
                outputArray[outputArrayIndex] = p;
                outputArrayIndex++;
            }

        }
        return new String(outputArray, 0, outputArrayIndex);

    }
}

1voto

rmuller Points 792

Dans la plupart des cas, l'utilisation de StringBuilder o substring est une bonne approche (comme déjà répondu). Cependant, pour un code dont les performances sont critiques, cela pourrait être une bonne alternative.

/**
 * Delete a single character from index position 'start' from the 'target' String.
 * 
 * ````
 * deleteAt("ABC", 0) -> "BC"
 * deleteAt("ABC", 1) -> "B"
 * deleteAt("ABC", 2) -> "C"
 * ````
 */
public static String deleteAt(final String target, final int start) {
    return deleteAt(target, start, start + 1);
} 

/**
 * Delete the characters from index position 'start' to 'end' from the 'target' String.
 * 
 * ````
 * deleteAt("ABC", 0, 1) -> "BC"
 * deleteAt("ABC", 0, 2) -> "C"
 * deleteAt("ABC", 1, 3) -> "A"
 * ````
 */
public static String deleteAt(final String target, final int start, int end) {
    final int targetLen = target.length();
    if (start < 0) {
        throw new IllegalArgumentException("start=" + start);
    }
    if (end > targetLen || end < start) {
        throw new IllegalArgumentException("end=" + end);
    }
    if (start == 0) {
        return end == targetLen ? "" : target.substring(end);
    } else if (end == targetLen) {
        return target.substring(0, start);
    }
    final char[] buffer = new char[targetLen - end + start];
    target.getChars(0, start, buffer, 0);
    target.getChars(end, targetLen, buffer, start);
    return new String(buffer);
}

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