• Post Reply Bookmark Topic Watch Topic
  • New Topic

problem with sorting Strings  RSS feed

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all , I have a problem with sorting Strings.

My problem is i have a tree of strings like
1 RootOne
1.1 SubIetm1
1.2 SubIetm2
1.3 SubIetm3
1.4 SubIetm4
....
....
1.9 SubIetm9
2 RootTwo


Like this , what happens is when the SubItems are more than 10 like

1.10 SubItem10
1.11 SubItem11
these items are placed before
1.2 SubItem2

like
1.1 SubIetm1
1.10 SubItem10
1.11 SubItem11
1.2 SubIetm2
1.3 SubIetm3
1.4 SubIetm4
....
....
1.9 SubIetm9

the total item that is 1.1 SubItem1 is String.

Could any one help me in this regard
 
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int compareTo(String anotherString)
Compares two strings lexicographically.

if you use this then it will return an int. Use this int to compare the string before it.

So if S1.compareTo(String S2) >0 then S1 is larger.
 
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'll have to write your own comparator and pass it to the sort() method. In your comparator, you'll extract the digits before the dot, convert them to an int and compare them. Then, if necessary, do the same for the digits following the dot (if there aren't any, treat that as a zero).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!