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.
Numerical sorting tweak?
- PuzzledGreatly
- Posts: 1303
- Joined: 29 Sep 2013, 22:18
- PuzzledGreatly
- Posts: 1303
- Joined: 29 Sep 2013, 22:18
Re: Numerical sorting tweak?
Think I found the answer. If I temporarily remove "Chapter " then I can just use a numerical sort
- SuperFoobar
- Posts: 83
- Joined: 23 Nov 2018, 15:14
Re: Numerical sorting tweak?
Use a custom sorting function by specifying the F parameter like so
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
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
Re: Numerical sorting tweak?
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%
Re: Numerical sorting tweak?
- 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.
- 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
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA