best way to truncate string Topic is solved

Get help with using AutoHotkey and its commands and hotkeys
User avatar
Posts: 6902
Joined: 19 Dec 2016, 01:58
Location: UK

best way to truncate string

23 Dec 2016, 02:17

I want to create a function called 'StrTruncate'
e.g. StrTruncate(ByRef vText, vLenNew)

what is the best way to truncate a string?
StringTrimRight, will be phased out
VarSetCapacity, potentially reduces the var capacity affecting future text append
insert a null character
some other way?
thank you!

PS regarding terminology
if a var is too small to append the desired text,
a new larger-capacity replacement var with the same name is created, and the text moved over,
is there a succinct term/phrase to describe this?
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA
Posts: 7088
Joined: 30 Sep 2013, 04:07
GitHub: Lexikos

Re: best way to truncate string  Topic is solved

24 Dec 2016, 00:48

StringTrimRight/StringLeft may be the most efficient since it avoids expression evaluation. You would have to benchmark it in the context of your script to be sure.

There is probably no other method that would be better than SubStr. If you insert a null character, you still need to call VarSetCapacity(var, -1) to update var's internal length field. The extra overhead would negate any possibility of performance gain. Any solution involving DllCall(..., "str", var) would have its own overhead.

VarSetCapacity(var, n) where n >= 0 will always truncate the value to zero characters (even if the capacity is non-zero), which isn't very useful. It will not restrict the length of future values; it will only change how long the value could be before its buffer needs to be reallocated.
a new larger-capacity replacement var with the same name is created, and the text moved over,
No new variable is created; the same variable is given a different value.

A new block of memory is allocated, the new string is copied into it, the string pointer internal to the variable is updated, then the old block of memory is freed. The variable's internal length field is also updated. The variable itself is a separate struct which is allocated only once and freed only when the script exits. &Var gives you the address of the block of memory containing the string value, not the actual variable.

There are some cases where a value is created in temporary memory (for a function's return value or result of concatenation) and this temporary memory is then attached to the variable directly instead of reallocating new memory for the variable.

Return to “Ask For Help”

Who is online

Users browsing this forum: AHKStudent, Coiler, Flipeador, just me, mcl, mikeyww, monstermunch14, Netocon, SteveTranslator, Tulevik, WOlfen and 62 guests