Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort a string alphabetically java [closed]

I want to sort a string in JAVA alphabetically, as follows Capital letter and lowercase letter followed AaBbCcDdEeFfGg. for example if I put AbaC return me AabC thanks!!

like image 596
adrisp Avatar asked Oct 19 '13 16:10

adrisp


3 Answers

Turn the String into a character array, then compare the int values of each character in your sort.

Methods needed: String.toCharArray();

like image 69
EyeOfTheHawks Avatar answered Oct 16 '22 08:10

EyeOfTheHawks


You can do this using Arrays.sort, if you put the characters into an array first. (It must be an array of Character objects rather than char primitives, in order to use a custom case-insensitive comparator.)

// put the characters into an array
Character[] chars = new Character[str.length()];
for (int i = 0; i < chars.length; i++)
    chars[i] = str.charAt(i);

// sort the array
Arrays.sort(chars, new Comparator<Character>() {
    public int compare(Character c1, Character c2) {
        int cmp = Character.compare(
            Character.toLowerCase(c1.charValue()),
            Character.toLowerCase(c2.charValue())
        );
        if (cmp != 0) return cmp;
        return Character.compare(c1.charValue(), c2.charValue());
    }
});

// rebuild the string
StringBuilder sb = new StringBuilder(chars.length);
for (char c : chars) sb.append(c);
str = sb.toString();
like image 13
Boann Avatar answered Oct 16 '22 07:10

Boann


You may try to look for Collections.sort and then try like this:-

Collections.sort(caps, String.CASE_INSENSITIVE_ORDER);

Something like this:-

private static Comparator<String> ALPHA_ORDER = new Comparator<String>() {
    public int compare(String str1, String str2) {
        int x = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
        if (x== 0) {
            x= str1.compareTo(str2);
        }
        return x;
    }
};

Collections.sort(list, ALPHA_ORDER);

EDIT:-

For sorting alphabetically in a string try like this:-

Collator col = Collator.getInstance(new Locale("en", "EN"));
String s = "AbaC";
String[] s1= s.split("");
Arrays.sort(s1, col);
String sorted = "";
for (int i = 0; i < s1.length; i++)
{
  sorted += s1[i];
}
System.out.println(sorted);
like image 8
Rahul Tripathi Avatar answered Oct 16 '22 08:10

Rahul Tripathi