Set string to a standard length

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
Archimede
Posts: 464
Joined: 25 Nov 2021, 09:49
Location: Switzerland / Italy

Set string to a standard length

Post by Archimede » 02 Dec 2022, 04:43

Hallo.
I need to set a string to a defined length; if it is short I need to add charaters to left or right; how is the better solution?
Thank you very much.

Rohwedder
Posts: 7550
Joined: 04 Jun 2014, 08:33
Location: Germany

Re: Set sting to a standard length

Post by Rohwedder » 02 Dec 2022, 04:59

Hallo,
try:

Code: Select all

Str := "abc"
MsgBox,% ">" Str "<`nLen: " StrLen(Str)
Str := Format("{:10}",Str) ;Len = 10
MsgBox,% ">" Str "<`nLen: " StrLen(Str)
Last edited by Rohwedder on 02 Dec 2022, 05:01, edited 1 time in total.

User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: Set sting to a standard length

Post by jNizM » 02 Dec 2022, 05:00

short example:

Code: Select all

MyString := "abcdef"
StringMinLenght := 10
CharsToAdd := "#"


if ((diff := StringMinLenght - StrLen(MyString)) > 0)
	loop % diff
		MyString .= CharsToAdd


MsgBox % MyString
Edit: Rohwedder was faster and his use of Format is also smarter
see https://www.autohotkey.com/docs/commands/Format.htm#Examples -> Padding with spaces
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile

Archimede
Posts: 464
Joined: 25 Nov 2021, 09:49
Location: Switzerland / Italy

Re: Set string to a standard length

Post by Archimede » 02 Dec 2022, 18:24

Thank you very much.
All two solution are useful for me.


User avatar
flyingDman
Posts: 2791
Joined: 29 Sep 2013, 19:01

Re: Set string to a standard length

Post by flyingDman » 03 Dec 2022, 22:24

Code: Select all

Str := "abcdef"
Min := 10
Chr := "#"
msgbox % substr(Str . StrReplace(Format("{:" Min "}", ""), " ", Chr),1, Min)
Truncates to Min length as well. Others above don't.
14.3 & 1.3.7

Post Reply

Return to “Ask for Help (v1)”