Click here to Skip to main content
15,886,074 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi,

Consider a simple string which contains numbers delimited by coma

Can anyone help me to sort this string in ascending order.

Example : string s = "20,3,33,44,2";
Posted

We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.

Try it yourself, you may find it is not as difficult as you think!

But it really isn't difficult:
1) Use string.Split to separate the numbers into separate strings.
2) Convert each string number to an integer, in an array of integers.
3) Sort the array.
4) Convert the integers back to strings using ToString
5) Use string.Join to rebuild the single string separated by commas.
 
Share this answer
 
Comments
Nirav Prabtani 17-Jul-14 6:42am    
my 5+
Ranjith Kumar 17-Jul-14 6:51am    
hi,

What if the string contains n numbers??

It would be not a proper approach based on ur suggestion.

Please share new solution
Richard MacCutchan 17-Jul-14 6:53am    
Of course it would be a proper approach. Have you actually tried to follow Griff's suggestions?
CPallini 17-Jul-14 6:57am    
If the string is huge you may consider parsing it and sort the numbers while the parsing is in progress, e.g. using a kind of insertion sort algorithm.
To get the result in sorted order, follow the simple steps of arrays.

1. Convert the string into an array by Split method
2. Make another integer type array of same length
3. put all the values in integer array by converting into integer.
4. Sort the integer array by for/foreach loop
5. Create a string from the sorted integer array to get desired result.



Option 2 with ArrayList

1. Convert the string into an array by Split method
2. Create an object of ArrayList class.
3. Add all the values of array into ArrayList object.
4. Sort the ArrayList object with Sort method. (arrList.Sort())
5. Create a string from the sorted ArrayList object to get desired result
 
Share this answer
 
Comments
Matt T Heffron 17-Jul-14 16:08pm    
Neither of these suggestions is a good one.
Griff's Solution 1 is a good solution.
And CPallini's note re: huge strings is relevant.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900