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"
No, nothing built in. Instead:
n = 5
str = "Ab"
result = replace(space(n), " ", str)
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With