-5

I want to achieve something like this:

String str = "Good Morning;
String subStr = str.substring(0,7);

Then I want to sort the letters in reverse order.

I want my output to be: ooMGd

meucaa
  • 1,455
  • 2
  • 13
  • 27
Py-Coder
  • 2,024
  • 1
  • 22
  • 28

3 Answers3

2

A simple way:

String str = "Good Morning";
String subStr=str.substring(0,7);
char[] arr = subStr.toCharArray();
Arrays.sort(arr); 
for(int i = arr.length - 1; i >= 0; i--) 
System.out.print(arr[i]);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

Try -

    public static void main(String[] args) throws IOException
{

    String str="Good Morning;" ;
    String[] subStr=str.substring(0,7).split("");
    Arrays.sort(subStr,Collections.reverseOrder());
    String s ="";
    for(int i=0;i<subStr.length;i++)
    {
        s+=subStr[i];
    }
    System.out.println(s);
}

Create a String array of from sub-string and sort that collection in reverse order. You have a reverse order sorted array of string now append them to a string you have a string with desired result.

Or A better Solution will be StringBuilder

     String str = "Good Morning";
     String s = new StringBuilder(str.substring(0, 7)).reverse().toString();
     System.out.println(s);

This will Also work correct.

Ajinkya Patil
  • 741
  • 1
  • 6
  • 17
0

Why don't you use a StringBuilder object?

Try this one-liner: (new StringBuilder(str.substring(0, 7))).reverse().toString();

And the complete example (including the sorting):

package testing.project;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        String str = "Good Morning";

        char[] sorted = new StringBuilder(str.substring(0, 7)).reverse().toString().toCharArray();
        Arrays.sort(sorted);

        String reversedString = new StringBuilder(new String(sorted)).reverse().toString();

        System.out.println(reversedString);
    }
}
Igoranze
  • 1,506
  • 13
  • 35