Java – Converting string to char and sort in descending order (ascii)

charjavastring

I am creating a program which will make the user input integer (one after another), stored in array and display the integers in descending order. The program also ask to the user to input a string convert it to char using string.toCharArray(). I've correctly done displaying the integer into descending order. The problem is I don't know how to display the char descendingly.

This is the code for the integer:

for(i=0;i<nums.length;i++){
        System.out.print("Enter value for index["+i+"] here --> ");
        nums[i]=Integer.parseInt(br.readLine());}

while(pass<nums.length){
        for(i=0;i<(nums.length-pass);i++){
            if(nums[i]<nums[i+1]){
                temp=nums[i];
                nums[i]=nums[i+1];
                nums[i+1]=temp;
            }
        }
        pass++;
}
System.out.println("\n\nThe numbers when sorted descendingly are :\n");
    for(i=0;i<nums.length;i++){
        System.out.println(nums[i]);

This is the code for the string to array. This is where i'm having problems. I don't have errors in running the program just it's just I don't how to do it correctly.

System.out.print("Input a string");
        String strValue= br.readLine();
        char[] chrValues;
        chrValues=strValue.toCharArray( );

while(flag<chrValues.length){
   for (c=0; c< (chrValues.length- flag); c++){
        if(chrValues[c]<chrValues[i+1]){
         tempo=chrValues[c];
                chrValues[c]=chrValues[c+1];
                chrValues[c+1]= tempo;}
   }
}
 flag++; 
 System.out.println("\n\nThe String when converted in character and sorted descendingly     are :\n");    
    for(c=0;i<chrValues.length;c++){
        System.out.println(chrValues[c]);}

By the way, I used flag as a temporary array storage.

Best Answer

You already have built-in method for that: -

    String str = "Rohit";
    char[] arr = str.toCharArray();

    System.out.println(arr);
    Arrays.sort(arr);   // Sort in Ascending order
    System.out.println(arr);

For descending order, you can define a Comparator and pass that to Arrays.sort() method..

You can use Arrays#sort and ArrayUtils#toObject for sorting in Descending order..

Here's how it works: -

    String str = "Rohit";
    char[] charArray = str.toCharArray();

    Character[] myCharArr = ArrayUtils.toObject(charArray);

    Arrays.sort(myCharArr, new Comparator<Character>() {

        @Override
        public int compare(Character char1, Character char2) {
            return char2.compareTo(char1);
        }
    });

    for (char val: myCharArr) {
        System.out.print(val);
    }