Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any build-in function in VBScript to repeat a string N-times?

There is a function in VBScript String(number,character) returns a string that contains a repeating character of a specified length. E.g.:

String(5, "A")     ' output: "AAAAA"

Is there any function to repeat a string? E.g.:

RepeatString(5, "Ab")     ' output "AbAbAbAbAb"
like image 837
Ivan Gerasimenko Avatar asked Oct 19 '16 12:10

Ivan Gerasimenko


3 Answers

No, nothing built in. Instead:

n      = 5
str    = "Ab"
result = replace(space(n), " ", str)
like image 152
Alex K. Avatar answered Sep 28 '22 10:09

Alex K.


For a general simple solution

Function RepeatString( number, text )
    Redim buffer(number)
    RepeatString = Join( buffer, text )
End Function

But if the text is short but the number of repetitions is high, this is a much faster solution

Function RepeatString( ByVal number, ByVal text )
    RepeatString=""
    While (number > 0)
        If number And 1 Then 
            RepeatString = RepeatString & text
        End If 
        number = number \ 2 
        If number > 0 Then
            text = text & text 
        End If 
    Wend
End Function
like image 20
MC ND Avatar answered Sep 28 '22 11:09

MC ND


For code brevity, the accepted answer is good. But the following function is literally 10 times as fast. And it's twice as fast as RepeatString(). It uses a little-known feature of Mid where it fills the remainder of a string buffer with a repeating pattern in one go...

Function Repeat$(ByVal n&, s$)
    Dim r&
    r = Len(s)
    If n < 1 Then Exit Function
    If r = 0 Then Exit Function
    If r = 1 Then Repeat = String$(n, s): Exit Function
    Repeat = Space$(n * r)
    Mid$(Repeat, 1) = s: If n > 1 Then Mid$(Repeat, r + 1) = Repeat
End Function
like image 29
Excel Hero Avatar answered Sep 28 '22 11:09

Excel Hero