1
votes

Convertir une chaîne en chaîne inversée à l'aide de la récursivité en Java

Aujourd'hui, j'essaie de convertir une chaîne en chaîne inversée , par exemple (Cat Is Running into Running Is Cat) mot par mot et non caractère

Running
Is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1

La sortie suivante est montré:

public static String reverse_recursion(String str) {
    if (str == null)
        return null;
    else {
        String Arry[] = str.split(" ");
        int n = Arry.length - 1;
        System.out.println(Arry[n] + "");
        return reverse_recursion(Arry[n - 1]);
    }
}

public static void main(String[] args) {
    reverse_recursion("Cat Is Running");
}

J'essaie de convertir une chaîne en chaîne inversée comme ci-dessus mais via la méthode de récursivité, mais cela semble trop déroutant. et afficher plus d'erreurs. Quelqu'un peut-il s'il vous plaît m'aider à le comprendre. Merci beaucoup

Running Is Cat BUILD SUCCESSFUL (total time: 0 seconds)

Ce code affiche la sortie suivante:

public class ReverseString_ {
    public static void reverse(String str) {
        String[] a = str.split(" ");
        for (int i = a.length - 1; i >= 0; i--) {
            System.out.println(a[i] + " ");
        }
    }

    public static void main(String[] args) {
        reverse("Cat Is Running");
    }
}

Ce code n'imprime pas l'index (0) pourquoi? quelqu'un peut-il m'aider à résoudre cette erreur s'il vous plaît


0 commentaires

3 Réponses :


1
votes

Cela devrait fonctionner:

public static String reverse(String s) {
    int idx = s.indexOf(" ");
    if (idx < 0) {
        // no space char found, thus, s is just a single word, so return just s itself
        return s;
    } else {
        // return at first the recursively reversed rest, followed by a space char and the first extracted word
        return reverse(s.substring(idx + 1)) + " " + s.substring(0, idx);
    }
}

public static void main(String[] args) {
    System.out.println(reverse("Cat Is Running"));
}


0 commentaires

1
votes

Cette solution pourrait être utile. Les commentaires expliquent assez bien le code.

public static String reverse_recursion(String str) {
    String[] arry = str.split(" ", 2); //Split into a maximum of 2 Strings

    if (arry.length > 1) { //If there is more than 1 word in arry
        //Return the reverse of the rest of the str (arry[1])           
        //and concatenate together with the first word (arry[0])
        return reverse_recursion(arry[1]) + " " + arry[0];
    }

    return arry[0]; //If less than or equal to 1 word, just return that word
}


3 commentaires

Merci beaucoup d'aide


@ user318974 Pas de problème. Si cette réponse vous a aidé, veuillez la marquer comme réponse acceptée :)


@MuhammadUsama Cela fonctionne maintenant correctement. Cas de test: Hello World From Here devient Here From World Hello .



0
votes

Vous enverrez le dernier élément du tableau la prochaine fois au lieu de la chaîne sans la chaîne précédemment imprimée.

Remplacez votre déclaration de retour par celle-ci, cela devrait fonctionner.

return reverse_recursion(n==0?null:str.substring(0,(str.length()-Arry[n].length())-1));


0 commentaires