Repeat a string: Difference between revisions
Content added Content deleted
(Undo revision 288477 by RayoGlauco (talk); contributed code belongs to #Delphi, #Free Pascal, or #Object Pascal (if anywhere)) |
|||
Line 1,547: | Line 1,547: | ||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
See [[#Delphi|Delphi]] or [[#Free Pascal|Free Pascal]], as standard Pascal does not know strings of unlimited length. |
See [[#Delphi|Delphi]] or [[#Free Pascal|Free Pascal]], as standard Pascal does not know strings of unlimited length. |
||
The example below shows how to repeat a string n times if possible, avoiding exceeding the maximum length. |
|||
<lang pascal> |
|||
program RepeatAString; |
|||
function StringRepeat(s: string; n: integer): string; |
|||
// Repeats s n times if possible, but avoids exceeding the maximum length |
|||
const |
|||
MaxStringLength = 254; |
|||
var |
|||
i, limit: integer; |
|||
begin |
|||
Result := ''; |
|||
// void string? |
|||
if s = '' then |
|||
exit; |
|||
// limit of repetitions |
|||
limit := MaxStringLength div Length(s); |
|||
// reduces n if needed |
|||
if limit < n then |
|||
n := limit; |
|||
// generates result |
|||
for i := 1 to n do |
|||
Result := Result + s; |
|||
end; |
|||
begin |
|||
// write some tests |
|||
writeln(StringRepeat('', 5)); |
|||
writeln(StringRepeat('ha', 5)); |
|||
writeln(StringRepeat('<----------------->', 100)); |
|||
// wait for <enter> |
|||
readln; |
|||
end. |
|||
</lang> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |