Tuesday, October 29, 2013

CMD DOS BATCH – Example of dynamic substring with subroutines

CMD DOS BATCH – Example of dynamic  substring with subroutines


This example illustrates the following:
  1. Substring
    1. Dynamic length based on the remaining length of the string from the start position.
  2. Subroutine
    1. With variable “by-reference
    2. Passing received variable from one subroutine to another
    3. Adding comma to each letter – in this case just using the count of characters. t



Test.cmd:


@echo off
cls
SETLOCAL enabledelayedexpansion
echo This example will pick up characters from 5 (b) to n in moon
set Stuff="The brown cow jumped over the moon"
echo Stuff starting=!Stuff!
call :mysr Stuff


goto:eof


:mysr
SETLOCAL enabledelayedexpansion
set SenSuffix=!%1!
set countTotal=0
call :StrToComSep SenSuffix countTotal
set startIndex=5
set /a length=!countTotal!-!startIndex!
Note -  Do not call the following statement inside a loop or if statement
CALL SET _SenSuffix=!%1:~%startIndex%,%length%!


echo _SenSuffix after modification=!_SenSuffix!
goto:eof


rem This subroutine takes a variable and places a comma after each character
rem and white space to be used as a deliminator
:StrToComSep <StrToDel> <countTotal>
setlocal enabledelayedexpansion
set string=!%1!#
set pos=0
:startLoop
       call set chr=%%string:~%pos%,1%%
       if !chr!==# goto done
       set varRebuild=!varRebuild!!chr!,
       set /a pos+=1
goto startLoop


:done
set varRebuild=!varRebuild:~0,-1!
ENDLOCAL & (SET %1=%varRebuild%
SET %2=%pos%)
goto:eof




Output:


This example will pick up characters from 5 (b) to n in moon
Stuff starting="The brown cow jumped over the moon"
_SenSuffix after modification=brown cow jumped over the moon"






tComma subroutine based on webpage:


No comments:

Post a Comment