Creating new String with sorted letters from a String word in Java
How do I create a String with alphabetical order letters taken from another String?
Let's say I have something like this
String theWord = "Hello World";
How do I compute the new String to make it look like"
dehllloorw
Which is theWord but sorted character by character in alphabetical order.
Thanks in advance开发者_StackOverflow
char[] chars = theWord.toCharArray();
Arrays.sort(chars);
String newWord = new String(chars);
See Arrays.sort()
& toCharArray()
Agreed, I stole the solution. But apparently, it's also important to strip whitespace and make everything lowercase:
char[] array = theWord.replaceAll("\\s+", "").toLowerCase().toCharArray();
Arrays.sort(array);
System.out.println(new String(array));
None of the above solutions are locale specific , therefore I came with this solution, it is not efficient , 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();
}
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];
}
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);
}
}
char[] chars2 = b.toLowerCase().toCharArray();
Arrays.sort(chars1);
String Ns1 = new String(chars1);
All the solutions were O(nlogn) as they are sorting the array. Instead we can take array[26] and do this in O(n). after you covert it into lowercase and remove spaces which are O(n), int[] ar=new int[26]; for(char c:s.toCharArray()) ar[c-'a']++; and then form the required string O(n).
精彩评论