Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Natural ordering of strings and numbers

 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What are the rules for ordering strings? As an example, the output of the following code example suggests that the ordering rules used is different for strings and numbers.



Output:



What is the best way to know how a string will be sorted?
 
Sebanti Sanyal
Ranch Hand
Posts: 58
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In case of String, "33" is not treated as per its numeric value. Since the first character '3' comes before 4, you see "33" before 4 and 5. However, TreeSet<Integer> compares the actual integer values.
 
Dan Drillich
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorting Strings explains that for ascii characters the sorting of words would be based upon their ASCII/Unicode character values and it's true for the Unicode set as well (which includes the ASCII set).

The article speaks about the case when the Unicode order is not what we have in mind as the proper sorting mechanism.

Regards,
Dan
 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dan Drillich wrote:Sorting Strings explains that for ascii characters the sorting of words would be based upon their ASCII/Unicode character values and it's true for the Unicode set as well (which includes the ASCII set).

The article speaks about the case when the Unicode order is not what we have in mind as the proper sorting mechanism.

Regards,
Dan


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic