RosettaCodeData/Task/Repeat-a-string/FreeBASIC/repeat-a-string.basic

30 lines
954 B
Plaintext

' FB 1.05.0 Win64
' A character is essentially a string of length 1 in FB though there is a built-in function, String,
' which creates a string by repeating a character a given number of times.
' To avoid repeated concatenation (a slow operation) when the string to be repeated has a length
' greater than one, we instead create a buffer of the required size and then fill that.
Function repeat(s As String, n As Integer) As String
If n < 1 Then Return ""
If n = 1 Then Return s
Var size = Len(s)
If size = 0 Then Return s ' empty string
If size = 1 Then Return String(n, s[0]) ' repeated single character
Var buffer = Space(size * n) 'create buffer for size > 1
For i As Integer = 0 To n - 1
For j As Integer = 0 To size - 1
buffer[i * size + j] = s[j]
Next j
Next i
Return buffer
End Function
Print repeat("rosetta", 1)
Print repeat("ha", 5)
Print repeat("*", 5)
Print
Print "Press any key to quit program"
Sleep