I have a char list ['a';'b';'c']
How do I convert this to the string "abc"?
thanks x
I have a char list ['a';'b';'c']
How do I convert this to the string "abc"?
thanks x
You can create a string of a length, equal to the length of the list, and then fold over the list, with a counter and initialize the string with the contents of the list... But, since OCaml 4.02, the string type started to shift in the direction of immutability (and became immutable in 4.06), you should start to treat strings, as an immutable data structure. So, let's try another solution. There is the Buffer
module that is use specifically for the string building:
# let buf = Buffer.create 16;;
val buf : Buffer.t = <abstr>
# List.iter (Buffer.add_char buf) ['a'; 'b'; 'c'];;
- : unit = ()
# Buffer.contents buf;;
- : string = "abc"
Or, as a function:
let string_of_chars chars =
let buf = Buffer.create 16 in
List.iter (Buffer.add_char buf) chars;
Buffer.contents buf
Since OCaml 4.07, you can use sequences to easily do that.
let l = ['a';'b';'c'] in
let s = String.of_seq (List.to_seq l) in
assert ( s = "abc" )
let cl2s cl = String.concat "" (List.map (String.make 1) cl)
Commonly used Base library also offers Base.String.of_char_list
© 2022 - 2024 — McMap. All rights reserved.
String.of_list
in batteries included. – Martamartaban