Results 1 to 11 of 11
  1. #1
    alexander.s is offline Member
    Join Date
    Aug 2008
    Posts
    8
    Rep Power
    0

    Default Sorting strings in java?

    Hi all,

    I'd like to know how to sort strings in java. Usually in C I'd do something like this:

    Java Code:
    for(i=0;i<length-1;i++)
    {
              for(j=0;j<length;j++)
              {
                       if(strcmp(name[i],name[j])>0)
                       {
                                 strcpy(tmp,name[i]);
                                 strcpy(name[i],name[j]);
                                 strcpy(name[j],tmp);
                       }
              }
    }
    I'd love to be able to do the same thing in Java, thanks in advance!

  2. #2
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Store them in a TreeSet, it ordered all elements in natural order. Or use Array.sort() on a string array.
    Last edited by Eranga; 08-30-2008 at 03:35 PM.

  3. #3
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Here is a simple example.

    Java Code:
    /**
     *
     * @author Eranga Tennakoon
     */
    public class SortArrays {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
            String[] arr = new String[]{"Java", "Forums", "Sun", "Apache",
            "JSP", "AJAX", "XML"};
            new SortArrays().sortStrings(arr);
        }
    
        private void sortStrings(String[] arr) {
            java.util.Arrays.sort(arr);
            for(int i = 0; i < arr.length; i++) {
                System.out.println(arr[i]);
            }
        }
    }

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,585
    Rep Power
    25

    Default

    The code in java would be translated one for one line of code.
    There are comparable methods to the C strcmp function in the String class. Java is a bit more wordy. Read the API doc for String.
    Use assignment statement vs using strcpy for the rest

  5. #5
    fishtoprecords's Avatar
    fishtoprecords is offline Senior Member
    Join Date
    Jun 2008
    Posts
    571
    Rep Power
    7

    Default

    Store them in any Collection implementation that has a "sort()" member function, and call it.

  6. #6
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

  7. #7
    fishtoprecords's Avatar
    fishtoprecords is offline Senior Member
    Join Date
    Jun 2008
    Posts
    571
    Rep Power
    7

    Default

    Quote Originally Posted by Eranga View Post
    In a TreeSet it's automatically happens, right?
    I think so, I'd have to check the javadocs. But you may need a comparitor of you want to support sorting in a special way.

    So the general answer is use a Collection, and a TreeSet is one.

    I don't know any of the asian languages, but even European ones have some non-obvious rules. For example, in Spanish, the "ch" pair is sorted as if it was a single character and sorts after "C" alone.

    Doing "strings" properly in a multi-language environment is a bit of a challenge. Java lets you do it "right" but its not all automatic.

  8. #8
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Yep you are right? If we think in English-only mindset sorting strings is easy. But in different languages, it wont.

    In TreeSet internally elements are sorted in natural order, and output as an array. See the example bellow.

    Java Code:
        public static void main(String[] args) {
            TreeSet at = new TreeSet();
            at.add("Java");
            at.add("Name");
            at.add("NetBeans");
            at.add("AJAX");
            
            System.out.println(at);
        }
    As you said, generally it comes from Java Collection framework, but specifically TreeSet. :)

  9. #9
    serjant's Avatar
    serjant is offline Senior Member
    Join Date
    Jun 2008
    Location
    Ukraine,Zaporozhye
    Posts
    487
    Rep Power
    7

    Default

    For different languages,other than English, we i think we should write a unicode convert function,and then creating unicode strings in TreeSet,maybe then it will sort.I will try to make a little test application now in Eclipse with Russian and Hebrew languages .

  10. #10
    serjant's Avatar
    serjant is offline Senior Member
    Join Date
    Jun 2008
    Location
    Ukraine,Zaporozhye
    Posts
    487
    Rep Power
    7

    Default

    I checked the TreeSet sorts the array only for English characters,for german with umlauts it sends the strings to the end of the TreeSet,in hebrew it doesn't sort it at all and the same in Russian,but the Arrays.sort(<some array of strings>) sorts everything,that means TreeSet doesn't support unicode while sorting.
    So in TreeSet the strings in other languages should be unicoded first and then sorted with Comparator

    Java Code:
    import java.util.*;
    public class JavaUnicode {
    	private TreeSet set=new TreeSet();
    
    	public JavaUnicode(){
    		
    		set.add("דויד");
    		set.add("קריש");
    		set.add("גרושה");
    		set.add("אלמן");
    		
    		System.out.println(set);
    		
    		
    		String[] s=new String[]{"דויד","קריש","גרושה","אלמן"};
    		//String[] s=new String[]{"David","Allan","Nick"};
    		
    		Arrays.sort(s);
    		for(int i=0;i<s.length;i++){
    			System.out.println(s[i]);
    		}
    		
    	}
    	
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		
    		new JavaUnicode();
    
    	}
    
    }

    the output:
    Java Code:
    [אלמן, גרושה, דויד, קריש]
    אלמן
    גרושה
    דויד
    קריש
    Last edited by serjant; 09-01-2008 at 12:06 AM.

  11. #11
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

Similar Threads

  1. Sorting CachedRowset
    By Sayed in forum Advanced Java
    Replies: 0
    Last Post: 07-18-2008, 12:14 PM
  2. Sorting an array of Strings
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-15-2008, 07:39 PM
  3. sorting problem
    By mcal in forum New To Java
    Replies: 1
    Last Post: 02-14-2008, 08:13 AM
  4. Help with Sorting Program
    By rhm54 in forum New To Java
    Replies: 3
    Last Post: 01-25-2008, 10:08 PM
  5. Heap Sorting
    By kesav2005 in forum New To Java
    Replies: 1
    Last Post: 11-13-2007, 04:04 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •