Solved a for loop question

February 3, 2020 at 05:42:23
Specs: Windows 10, 8GB
Trying to write a simple loop for doing the following in Windows CMD:

I would input a word, for example "example" (without the quotes), and then the loop should do something with the word:

example

then, in the following loop run it should do something with the same word, but with only the last character removed:

exampl

and then it should do the same with the word with one character removed:

examp

.. until we are left with 1 character (the first character of the word):

e


I have the current script, but it goes wrong on the line where I try to create the "p_partial_text" variable. Can you tell me how to get this done. Usage of delayedexpansion is not required. I have hardcoded "example" and the number "7" to avoid unnecessary code, I am replacing this with real variables in the end.

@echo off

setlocal enabledelayedexpansion

set p_input_text=example

for /L %%A in ( 7 , -1 , 1 ) do call :substring %%A

goto :EOF

:substring
set p_length=%1
set p_partial_text=%p_input_text:~0,!p_length!%
echo %p_partial_text%
goto :EOF

message edited by Looge


See More: a for loop question

Reply ↓  Report •

#1
February 3, 2020 at 22:42:54
✔ Best Answer
Mostly you're just missing the ~-1 option. Here's sample:
@echo off & setlocal
set x=
set /p x=string:
:a
set k=%x:~-1%
echo last: %k%
set x=%x:~0,-1%
echo string: "%x%"
if "%x%" equ "" goto :eof
goto :a

Reply ↓  Report •

#2
February 4, 2020 at 01:07:18
That works good enough, the FOR loop was also optional indeed :)

I knew there was a simplier way to do the same!


Thanks nbrane


Reply ↓  Report •

#3
February 4, 2020 at 19:12:05
Ah, yes, the loop works too, if you reverse the ! and the %:
@echo off
setlocal enabledelayedexpansion
set p_input_text=example
for /L %%A in ( 7 , -1 , 1 ) do call :substring %%A
goto :EOF

:substring
set p_length=%1
set p_partial_text=!p_input_text:~0,%p_length%!
echo %p_partial_text%
goto :EOF


Reply ↓  Report •
Related Solutions


Ask Question