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
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]);
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.
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);
}
}