Visual LISP, AutoLISP and General Customization
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

sorting a string of numbers

5 REPLIES 5
SOLVED
Reply
Message 1 of 6
markruys2
1595 Views, 5 Replies

sorting a string of numbers

acad_strlsort will sorts strings, but what if my list looks like

("1" "2" "3" "10" "11" "12" "20")

i am sure i have seen it done ina simple way using vl-sort or vl-sort-i

but am not able to find... can someone help

TIA

5 REPLIES 5
Message 2 of 6
_Tharwat
in reply to: markruys2

Covert strings (numbers) to integers then re list them again into strings ..

 

(setq l '("1" "2" "3" "10" "11" "12" "20"))

  (foreach x l (setq lst (cons (atoi x) lst)))
  (setq lst1 (vl-sort lst '<))
  (foreach x lst1 (setq lst2 (cons (itoa x) lst2)))
   (reverse lst2)

 Return ..

 

("1" "2" "3" "10" "11" "12" "20") 

 

 Tharwat

Message 3 of 6
Kent1Cooper
in reply to: markruys2


@markruys2 wrote:

acad_strlsort will sorts strings, but what if my list looks like

("1" "2" "3" "10" "11" "12" "20")

i am sure i have seen it done ina simple way using vl-sort or vl-sort-i

but am not able to find... can someone help

TIA


You can have the conversion to numbers for comparison occur within the sorting function:

 

Command: (setq test '("21" "4" "35" "2" "1" "14"))
("21" "4" "35" "2" "1" "14")

Command: (vl-sort test '(lambda (a b) (< (atoi a) (atoi b))))
("1" "2" "4" "14" "21" "35")

 

Or, to use your example list, since it's already sorted one way, maybe you want to sort it in the other direction:

 

Command: (setq test '("1" "2" "3" "10" "11" "12" "20"))
("1" "2" "3" "10" "11" "12" "20")

Command: (vl-sort test '(lambda (a b) (> (atoi a) (atoi b))))
("20" "12" "11" "10" "3" "2" "1")

Kent Cooper, AIA
Message 4 of 6
dale_fugier
in reply to: markruys2

If you use DOSLib, you could just use the dos_strsort function:

 

http://www.en.na.mcneel.com/doslib/string_functions/dos_strsort.htm

 

Use the "logical" sorting mode.

 

 -- Dale

Message 5 of 6
dbroad
in reply to: dale_fugier

Welcome back Dale.

Architect, Registered NC, VA, SC, & GA.
Message 6 of 6
Kent1Cooper
in reply to: Kent1Cooper


@Kent1Cooper wrote:

....

Command: (vl-sort test '(lambda (a b) (< (atoi a) (atoi b))))
 

Or, to use your example list, since it's already sorted one way, maybe you want to sort it in the other direction:

....

Command: (vl-sort test '(lambda (a b) (> (atoi a) (atoi b))))
....


Another [and slightly shorter] way to do those same sorts, without the use of (lambda):

 

Command: (setq test '("21" "4" "35" "2" "1" "14"))
Command: (mapcar 'itoa (vl-sort (mapcar 'atoi test) '<))
("1" "2" "4" "14" "21" "35")

 

Command: (setq test '("1" "2" "3" "10" "11" "12" "20"))
Command: (mapcar 'itoa (vl-sort (mapcar 'atoi test) '>))
("20" "12" "11" "10" "3" "2" "1")

Kent Cooper, AIA

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk Design & Make Report

”Boost