Str Repeat Implementation using Windows Batch Script


The str_repeat function is a commonly used function that allows you to print/generate a string that is filled with a number of common patterns. For example:

str_repeat(3, “Hello “) gives “Hello Hello Hello ”

The following is a quick Windows Batch Script that does the same thing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@echo off
setlocal enableDelayedExpansion
 
if [%1]==[] goto help
if [%2]==[] goto help
 
set s=
for /L %%v in (1,1,%1) do (
        set s=!s!%~2
)
echo !s!
 
goto :eof
 
:help
        echo Usage %0 count pattern
@echo off
setlocal enableDelayedExpansion

if [%1]==[] goto help
if [%2]==[] goto help

set s=
for /L %%v in (1,1,%1) do (
        set s=!s!%~2
)
echo !s!

goto :eof

:help
        echo Usage %0 count pattern

For example:

1
2
3
4
5
6
7
$ str_repeat.cmd 3 *
***
$ str_repeat.cmd 5 "ab"
ababababab
 
$ str_repeat.cmd 2 "Hello World"
Hello WorldHello World
$ str_repeat.cmd 3 *
***
$ str_repeat.cmd 5 "ab"
ababababab

$ str_repeat.cmd 2 "Hello World"
Hello WorldHello World

We enable the “enableDelayedExpansion” to allow variable substitution at runtime. And we use the for /L to loop for the given number of times.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
190 words
Last Post: Algorithm to Compute the Maximum Population Year
Next Post: Teaching Kids Programming - Depth First Search Algorithm to Delete Even Leaves Recursively From Binary Tree

The Permanent URL is: Str Repeat Implementation using Windows Batch Script

Leave a Reply