Numerical sorting tweak?

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
User avatar
PuzzledGreatly
Posts: 1303
Joined: 29 Sep 2013, 22:18

Numerical sorting tweak?

22 Apr 2019, 21:36

I have text files named from "Chapter 1" through to "Chapter 10". If I loop through the files to put the names into a variable the list ends up as follows:

Chapter 1
Chapter 10
Chapter 2
Chapter 3...

How to fix this so they are in order with Chapter 10 coming after Chapter 9? Do I really need to rename the files so they are Chapter 01, Chapter 02 etc or is there a smarter way? Thanks.
User avatar
PuzzledGreatly
Posts: 1303
Joined: 29 Sep 2013, 22:18

Re: Numerical sorting tweak?

22 Apr 2019, 21:39

Think I found the answer. If I temporarily remove "Chapter " then I can just use a numerical sort
User avatar
SuperFoobar
Posts: 83
Joined: 23 Nov 2018, 15:14

Re: Numerical sorting tweak?

22 Apr 2019, 21:52

Use a custom sorting function by specifying the F parameter like so

Code: Select all

List =
(
Chapter 3
Chapter 1
Chapter 999
Chapter 10
Chapter -69
Chapter 2
)

Sort, List, F IntegerSort

IntegerSort(a1, a2)
{
    a1 := StrReplace(a1, "Chapter ")
	a2 := StrReplace(a2, "Chapter ")
	return a1 - a2
}

Msgbox % list
The function requires that you return a positive integer if a1 is > a2, negative number if a1 < a2 and 0 if they're equal... so return a1 - a2 works perfect. We also use a string replace to remove the "chapter " part so the numbers can be compared
just me
Posts: 9575
Joined: 02 Oct 2013, 08:51
Location: Germany

Re: Numerical sorting tweak?

23 Apr 2019, 04:55

For the special case 'fix prefix':

Code: Select all

List =
(
Chapter 3
Chapter 1
Chapter 999
Chapter 10
Chapter -69
Chapter 2
)

Sort, List, P9 N ; sort starting at position 9

Msgbox, %List%
User avatar
jeeswg
Posts: 6902
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Numerical sorting tweak?

23 Apr 2019, 08:32

- You can make use of the StrCmpLogicalW function, to sort items like Explorer sorts file names.
- Note: there is no StrCmpLogicalA or ANSI equivalent function, however, by using 'WStr', you can use the function with ANSI versions of AutoHotkey.
- WStr converts ANSI strings into Unicode strings in ANSI versions of AHK. WStr leaves Unicode strings unchanged in Unicode versions of AHK.

Code: Select all

q:: ;sort using StrCmpLogicalW
List := "
(
Chapter 3
Chapter 1
Chapter 999
Chapter 10
Chapter -69
Chapter 2
)"

Sort, List, F SortStrCmpLogical
MsgBox, % List
return

SortStrCmpLogical(vTextA, vTextB, vOffset) ;for use with AHK's Sort command
{
	local
	vRet := DllCall("shlwapi\StrCmpLogicalW", "WStr",vTextA, "WStr",vTextB)
	return vRet ? vRet : -vOffset
}
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Mateusz53, mikeyww and 312 guests