Is it possible to use variables in a substring operation?

Microsoft Windows
Post Reply
Rekrul
Posts: 3
Joined: 2021-Aug-15, 11:29 pm

Is it possible to use variables in a substring operation?

Post 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.
User avatar
Simon Sheppard
Posts: 49
Joined: 2021-Jul-10, 7:46 pm
Contact:

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

Post 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!
Post Reply