Repeat a string: Difference between revisions

→‎{{header|OCaml}}: Bytes instead of String
(Add Kotlin)
(→‎{{header|OCaml}}: Bytes instead of String)
Line 1,012:
 
=={{header|OCaml}}==
Since Ocaml 4.02 strings are immutable, as is convenient for a functional language. Mutable strings are now implemented in the module Bytes.
<lang ocaml>let string_repeat s n =
let len = StringBytes.length s in
let res = StringBytes.create(n * len) in
for i = 0 to pred n do
StringBytes.blit s 0 res (i * len) len;
done;
Bytes.to_string res (* not stricly necessary, the bytes type is equivalent to string except mutability *)
(res)
;;</lang>
which gives the signature<lang ocaml> val string_repeat : bytes -> int -> string = <fun></lang>
 
testing in the toplevel:
Line 1,025 ⟶ 1,027:
- : string = "HiuoaHiuoaHiuoa"</lang>
 
Alternately create an array initialized to s, and concat:
<lang ocaml>let string_repeat s n =
String.concat "" (Array.to_list (Array.make n s))
Line 1,035 ⟶ 1,037:
;;</lang>
 
To repeat a single character use:
<lang ocaml>String.make 5 '*'</lang>
 
Anonymous user