Search code examples
windowsbatch-filevariablessubstring

Windows Batch SET with Variable Substring Length?


Take this simple example:

@ECHO OFF
SET /P phrase="Enter Word : "
SET /a rnum=%random% %%10 +1
ECHO %phrase%
ECHO %rnum%

SET rchar=%phrase:~0,%rnum%%

ECHO %rchar%
Pause

I just want to be able to pass that rnum variable to pick that as the character chosen from the left of that user entered word to that random character.

I can't seem to figure out how to pass that as a variable.

I tried with enabledelayedexpansion with no luck:

@ECHO OFF
SET /P Phrase="Enter Word : "
SET /a rnum=%random% %%10 +1
ECHO %phrase%
ECHO %rnum%
setlocal enabledelayedexpansion
SET rchar=!phrase:~0,%rnum%!
endlocal
ECHO %rchar%
Pause

So how do I pass rnum as a variable in this instance? Thanks for any assistance.


Solution

  • Here's a simple modification of your example delayed expansion code, which shows one method of maintaining your variable value beyond endlocal:

    @ECHO OFF
    SET /P "phrase=Enter Word : "
    SET /A rnum = %RANDOM% %% 10 + 1
    ECHO %phrase%
    ECHO %rnum%
    SETLOCAL ENABLEDELAYEDEXPANSION
    FOR %%G IN ("!phrase:~0,%rnum%!") DO ENDLOCAL & SET "rchar=%%~G"
    ECHO rchar=%rchar%
    PAUSE
    

    The above example should be fine, as long as the end user does not begin to input strings with problematic characters. If you wanted to make it a little more robust for such scenarios then perhaps this will help:

    @Echo Off
    SetLocal EnableExtensions DisableDelayedExpansion
    
    :AskString
    Rem Get interactive string input
    Set "String="
    Set /P String="Enter Word : "
    If Not Defined String GoTo AskString
    Set String
    
    Rem Generate a random integer 1..10
    Set /A "Integer = (%RANDOM% %% 10) + 1"
    Set Integer
    
    Rem Create a substring variable using %String% and %Integer%
    Echo %%SubString%% = %%String:~0,%Integer%%%
    SetLocal EnableDelayedExpansion
    For /F Delims^=^ EOL^=^ UseBackQ %%G In ('"!String:~0,%Integer%!"') Do (
        EndLocal
        Set "SubString=%%~G"
    )
    Set SubString
    
    Pause
    

    Please note that the above code uses Set Variable to display the variable name along side its value. If your variable contains certain poison characters just using Echo %Variable% may not work, and you would probably be better off keeping delayed expansion enabled at that time.