You are not logged in.
Pages: 1
Greetings,
There is a batch file to count the length of a string, and I was wondering if someone could help me understand it.
1. setLocal EnableDelayedExpansion
2. set "s=#%~1"
3. set "len=0"
4. for %%N in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
5. if "!s:~%%N,1!" neq "" (
6. set /a "len+=%%N"
7. set "s=!s:~%%N!"
8. )
9. )
10. endLocal&if "%~2" neq "" (set %~2=%len%) else echo %len%
Line 2: What does the "#" do in variable string?
Line 3: Why is the variable name and string in quotes?
Line 4: What is the significance of the declining numbers, beginning at 4096?
There was another discussion, but it began in 2008, so I thought I would start a new topic.
Thanks,
Shane.
Last edited by Shane (05 Jan 2020 20:14)
Windows 10 Home 64-bit
Offline
Line 2: What does the "#" do in variable string?
Two things: it ensure the string is never empty and it adds one to the length of the string, on line 5 the IF test is looking for the 'next' character, so it would measure 1 short without this adjustment.
Line 3: Why is the variable name and string in quotes?
The quotes just allow the value to contain punctuation, in this case they arent really needed, I guess they are just there for consistency.
Line 4: What is the significance of the declining numbers, beginning at 4096?
The maximum length of a CMD variable is 8191 characters, rather than test every possibility going through a loop 8191 times, the script starts with a test that is roughly half way through the maximum.
If no match is found, it then starts at 1/4 then 1/8 etc until some data is found.
When a match is found, line 7. removes that portion from the string, the loop then continues iterating through the remaining part until the entire string has been counted.
If you knew for sure that the string would contain less than say 100 characters, then you could miss out some of those numbers starting at 64 to speed it up a little.
Offline
Line 2:
I thought the "#" was modifying the string. It sounds like it is part of the string.
Line 3:
I removed the quotes and it still seems to work.
Line 4:
I like the way this is done. I never would have thought of it.
Thanks for helping me understand it.
Windows 10 Home 64-bit
Offline
Line 2: I thought the "#" was modifying the string. It sounds like it is part of the string.
Yes... part of the string.
Line 3: I removed the quotes and it still seems to work.
Yes. It will still work in this case. However it is best practice to quote the string as shown so that it will work correctly if:
a. trailing white space character (that would be part of variable that you would not see without quotes)
b. whitespace or special characters contained in string
Windows Shell Scripting and InstallShield
Offline
Pages: 1