Substring extraction fails in reverse order

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Alsart
Posts: 4
Joined: 29 Nov 2024 17:58

Substring extraction fails in reverse order

#1 Post by Alsart » 29 Nov 2024 18:12

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

OJBakker
Expert
Posts: 93
Joined: 12 Aug 2011 13:57

Re: Substring extraction fails in reverse order

#2 Post by OJBakker » 30 Nov 2024 04:42

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

Alsart
Posts: 4
Joined: 29 Nov 2024 17:58

Re: Substring extraction fails in reverse order

#3 Post by Alsart » 01 Dec 2024 12:47

Very clever solution, exactly what I need.
Thanks

Post Reply