I'm currently trying to make a mini dictionary. To do it i need to learn how to sort strings in alphabetical order. Can anyone tell me or give me a hint as to how am i going to sort the words in alphabetical order.

The String method compareToIgnoreCase should do the trick. For example:

int result = string1.compareToIgnoreCase(string2);
// here result < 0 if string1 > string2
// or result = 0 if string1 == string2
// or result > 0 if string1 < string2

That should give you a start anyway. Have a go and see what you can come up with.

> Can anyone tell me or give me a hint as to how am i going to sort the words
> in alphabetical order.

Look into the Collections#sort method which takes a Comparator instance to facilitate custom sorting.

The String method compareToIgnoreCase should do the trick. For example:

int result = string1.compareToIgnoreCase(string2);
// here result < 0 if string1 > string2
// or result = 0 if string1 == string2
// or result > 0 if string1 < string2

That should give you a start anyway. Have a go and see what you can come up with.

Are you sure about that? I thought it just added the value of the separate characters for each String, then compared those values. Which would not put them in alphabetical order. I'm not saying you're wrong, just curious.

Are you sure about that? I thought it just added the value of the separate characters for each String, then compared those values. Which would not put them in alphabetical order. I'm not saying you're wrong, just curious.

No, the compareToIgnoreCase method's documentation in the API states that it compares the two strings "lexicographically", meaning that they are compared according to where they would be placed in a dictionary. The documentation also states that locales are ignored, but I'm not entirely sure what they mean by that, perhaps accented characters as seen in French or the umlaut in German are not considered?

import java.util.*;

class StringSort
{

    public static void main(String args[])
    {

        String str1="Hi how are you";
        String []str;

        str=str1.split(" ");

        String []str2=new String[str.length];

        for(int i=0;i<str.length;i++)
        {
            str2[i]=str[i].toUpperCase();       
        }

        Arrays.sort(str2);

        for(int l=0;l<str2.length;l++)
        {
            System.out.println(str2[l]);
        }
    }
}
/*Output:
C:\Users\asd>java StringSort
ARE
HI
HOW
YOU
*/

Awesome! Eyndyel has been waiting TWO YEARS for someont to post that code. Thanks!

Seriously - what was the point of posting this, aside from showing off that you know how to sort Strings? (Hint: if that's what you've got to brag about, you might want to keep your head down and learn some new tricks.)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.