How to get formatted string in OCaml?

In OCaml, I can use Printf.printf to output a formatted string, e.g.

 Printf.printf "Hello %s %d\n" world 123 

However, printf is a way out.


I want to use not for output, but for the string. For example, I want

 let s = something "Hello %s %d\n" "world" 123 

then I can get s = "Hello World 123"


How can i do this?

+7
source share
2 answers

You can use Printf.sprintf:

 # Printf.sprintf "Hello %s %d\n" "world" 123;; - : string = "Hello world 123\n" 
+12
source

You can do it:

 $ ocaml OCaml version 4.00.1 # let fmt = format_of_string "Hello %s %d";; val fmt : (string -> int -> '_a, '_b, '_c, '_d, '_d, '_a) format6 = <abstr> # Printf.sprintf fmt "world" 123;; - : string = "Hello world 123" 

The format_of_string function (as the name implies) converts a string literal to a format. Note that formats must ultimately be constructed from string literals, because they involve compiler magic. For example, you cannot read a string and use it as a format. (That would not be typical.)

+5
source

All Articles