Page 1 of 1

Is it possible to use variables in a substring operation?

Posted: 2021-Nov-08, 2:08 am
by Rekrul
I want to do something like this;

Code: Select all

set String=1234567890
set /p x=Number of desired characters?
echo %String:~0,%x%%
Where the substring operation would return however many characters the user enters. If they enter "5", they'd get "12345".

I've tried it using Delayed Expansion and that didn't seem to work either.

I can use a For token in the substring, and I've figured out a work-around for what I want to do, but it would be much simpler if there was a way to directly use a variable.

Is this possible?

EDIT:

After much experimentation, it seems that enabling delayed expansion and using !String:~0,%x%! works.

Re: Is it possible to use variables in a substring operation?

Posted: 2021-Nov-11, 12:26 am
by Simon Sheppard
Thats a very interesting usage, you are using DelayedExpansion against a string expression rather than a variable I didn't realise that was possible, but it works!

Re: Is it possible to use variables in a substring operation?

Posted: 2022-Jan-23, 1:07 pm
by User04
It's also possible to achieve the same result without delayed expansion. Since ECHO is an internal command, the following works:

Code: Select all

set String=1234567890
set /p x=Number of desired characters?
call echo %%String:~0,%x%%%
See also: The "Advanced Usage of :~" section in How-to: Extract part of a variable (substring)