153 votes

Trier une seule chaîne de caractères en Java

Existe-t-il un moyen natif de trier une chaîne de caractères par son contenu en java ? Par exemple

String s = "edcba"  ->  "abcde"

0voto

cron8765 Points 11

Vous pouvez également écrire un algorithme de tri par comptage pour trier tous les caractères d'un tableau si vous souhaitez réduire votre complexité temporelle dans le pire des cas de nlogn a n

-1voto

Tarun Jadhav Points 11
public static void main(String[] args) {
    String str = "helloword";   
    char[] arr;
    List<Character> l = new ArrayList<Character>();
    for (int i = 0; i < str.length(); i++) {
        arr = str.toCharArray();
        l.add(arr[i]);

    }
    Collections.sort(l);
    str = l.toString();
    System.out.println(str);
    str = str.replaceAll("\\[", "").replaceAll("\\]", "")
            .replaceAll("[,]", "");
    System.out.println(str);

}

-2voto

Sans utiliser les Collections en Java :

import java.util.Scanner;

public class SortingaString {
    public static String Sort(String s1)
    {
        char ch[]=s1.toCharArray();         
        String res=" ";

        for(int i=0; i<ch.length ; i++)
        {
            for(int j=i+1;j<ch.length; j++)
            {
                if(ch[i]>=ch[j])
                {
                    char m=ch[i];
                    ch[i]=ch[j];
                    ch[j]=m;
                }
            }

            res=res+ch[i];

        }

        return res;
    }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("enter the string");

        String s1=sc.next();
        String ans=Sort( s1);

        System.out.println("after sorting=="+ans);
    }
}

Sortie :

entrez la chaîne==

trier

après le tri== ginorst

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