user7873306
user7873306

Reputation:

Slicing Strings Using Variables In Batch

So I want a program like this:

Enter number: 
5
Giving first 5 characters of string "apple pie"...
apple

I have tried something like this

set characters=5
set "string=apple pie"

set string=%string:~0, %characters%%

But it's not working, any idea why?

Upvotes: 0

Views: 796

Answers (1)

elzooilogico
elzooilogico

Reputation: 1705

either rewrite

set string=%string:~0, %characters%%

as

call set "string=%%string:~0, %characters%%%"

or use delayed expansion

@echo off
set characters=5
set "string=apple pie"

setlocal enabledelayedexpansion
set "string=!string:~0, %characters%!"
echo %string%

see Variables in batch not behaving as expected

Upvotes: 2

Related Questions