DONT WORK: string input / if construct: output part of string with variable

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Chronofos
Posts: 6
Joined: 16 Mar 2024 11:09

DONT WORK: string input / if construct: output part of string with variable

#1 Post by Chronofos » 08 Apr 2024 01:11

Hello, I'm asking for help because I can't get any further on my own.

I'm trying to take part of an input string (string: ~0.1%) and create a query using if-else-construct.
And it works correctly with (Input "1" as first character)

Code: Select all

@echo off
cls
setlocal enabledelayedexpansion

SET /p "string=Insert characters:  "

ECHO Ouput part of string - first character=   !string:~0,1!

if %string:~0,1% EQU 1 (
   ECHO Output if first character = 1:   Condition True
   ) else (
   ECHO Output if not first character = 1:    Condition False
)
But if I replace one of the parameters of the string output (string:~0.1%) with a variable (string:~variable,1) the program doesn't work correctly (Input "1" as first character)!
I never reach "Condition True".

Code: Select all

@echo off
cls
setlocal enabledelayedexpansion

SET /p "string=Insert characters:  "

SET /a counter=0
ECHO counter =   %counter%

ECHO Ouput part of string - first character=   !string:~0,1!

if %string:~%counter%,1% EQU 1 (
   ECHO Output if first character = 1:   Condition True
   ) else (
      ECHO Output if not first character = 1:    Condition False
)
What am I doing wrong? Or is it not possible?

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: DONT WORK: string input / if construct: output part of string with variable

#2 Post by Squashman » 08 Apr 2024 07:32

Well you have delayed expansion enabled. It would help if you used it.

Code: Select all

if !string:~%counter%,1! EQU 1

Post Reply