Convert char to string in OCaml

Viewed 24662

I want to convert a char to a string but I haven't found a function string_of_char. I want to do that using only functions from Pervasives.

4 Answers

If you don't want any dependencies outside the standard library that ships with OCaml*, you can also convert a character to a string using a format string.

Create a 1-character string out of a character

Printf.sprintf "%c" ch

(note that capital C) Create a string containing the OCaml notation for the given character

Printf.sprintf "%C" ch

for example:

# Printf.sprintf "%C" '\\';;
- : string = "'\\\\'"
# Printf.sprintf "%C" 'a';;
- : string = "'a'"

*Printf is not itself part of Pervasives

Related