Hi,
I want to extract all the characters, char by char, contained in a variable, without knowing the length of the string. For example using the syntax for substring extraction and extracting from left to right:
set str=ABC
set c=%str:~0,1% gives in var c the first char A, ..., set c=%str:~2,1% gives the last char C
And the end of the string can be detected because when you extract a char that is outside the string it gives an empty variable, for example:
set c=%str:~3,1% gives an empty variable
But if you extract from right to left, the detection of the beginning of the string fails, for example:
set c=%str:~-1,1% gives the last char C, ..., set c=%str:~-3,1% gives the first char A
But set c=%str:~-4,1% gives always the first char A instead of an empty string and it is not possible to detect the beginning of string.
I have tested it in Win7, Win10 and Win11 and it fails in all of them.
As I said, I want to extract char by char in reverse order without obtaining first the length of the string.
Any way to solve this issue?
Thanks
Substring extraction fails in reverse order
Moderator: DosItHelp
Re: Substring extraction fails in reverse order
Code: Select all
@echo off
cls
setlocal
set "Str=ABCDE"
set "StrTmp=%Str%"
if not defined StrTmp goto :end
set /a i=0
:loop
set /a i+=1
rem extract last character
set Ar[%i%]=%StrTmp:~-1,1%
rem remove last character from string
set StrTmp=%StrTmp:~0,-1%
rem check if string still exists (has more characters)
if defined StrTmp goto :loop
:end
set Str
set Ar
endlocal
pause
Re: Substring extraction fails in reverse order
Very clever solution, exactly what I need.
Thanks
Thanks