formatprintfocaml

What's the OCaml equivalent of C's printf("%.3s"), i.e, specifying a maximum width for a string argument?


In C, one can write:

printf("%.3s", "foobar");

To get foo printed as a result (that is, print the initial part of a string).

In OCaml, Printf.printf "%.3s" "foobar" results in:

Error: invalid format "%.3s": at character number 0, `precision' is incompatible with 's' in sub-format "%.3s"

What is the best way to print the initial part of a string in OCaml?


Solution

  • Starting with OCaml 5.3, you can use pp_print_substring and a %a specifier:

    let () = 
      Format.printf "hel=%a@." (Format.pp_print_substring ~pos:0 ~len:3) "hello"