Creating a new line with sorted letters from a string word in Java

How to create a string with alphabetical order letters taken from another string?

Say I have something like this

String theWord = "Hello World"; 

How to calculate a new line so that it looks like this:

dehllloorw

This is a character, but sorted by character in alphabetical order.

Thanks in advance

+6
source share
7 answers
 char[] chars = theWord.toCharArray(); Arrays.sort(chars); String newWord = new String(chars); 
+25
source
+10
source

I agree, I stole the decision. But apparently it’s also important to break the spaces and make all the lowercase letters:

 char[] array = theWord.replaceAll("\\s+", "").toLowerCase().toCharArray(); Arrays.sort(array); System.out.println(new String(array)); 
+4
source

None of the above solutions depend on the locale, so I came up with this solution, it is inefficient, but it works very well.

 public static String localeSpecificStringSort(String str, Locale locale) { String[] strArr = new String[str.length()]; for(int i=0;i<str.length();i++){ strArr[i] = str.substring(i,i+1); } Collator collator = Collator.getInstance(locale); Arrays.sort(strArr, collator); StringBuffer strBuf = new StringBuffer(); for (String string : strArr) { strBuf.append(string); } return strBuf.toString(); } 
+2
source
 char[] arr = new char[theWord.length()]; for(int i=0;i<theWord.length;i++) { arr[i]=theWord.charAt(i); } for(int i=0;i<theWord.length();i++) for(int j=0;j<theWord.length();j++) { char temp = arr[i]; arr[i]=arr[j]; arr[j]=temp; } int size=theWord.length(); theWord=""; for(int i=0;i<size;i++) { theWord+=arr[i]; } 
+1
source
 import java.util.Arrays; import java.util.Scanner; // re arrange alphabets in order public class RearrangeAlphabets { @SuppressWarnings("resource") public static void main(String[] args) { String theWord; Scanner in = new Scanner(System.in); System.out.println("Enter a string to rearrange: \n"); theWord = in.nextLine(); int length = theWord.length(); System.out.println("Length of string: "+length); char[] chars=theWord.toCharArray(); Arrays.sort(chars); String newWord=new String(chars); System.out.println("The Re-Arranged word : "+newWord); } } 
0
source
 char[] chars2 = b.toLowerCase().toCharArray(); Arrays.sort(chars1); String Ns1 = new String(chars1); 
0
source

Source: https://habr.com/ru/post/889965/


All Articles