Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml - How do I convert int to string?

Tags:

string

int

ocaml

How do I convert an int to a string? Example: 1 to "1".

like image 572
EBM Avatar asked Apr 03 '12 02:04

EBM


People also ask

How do I compare strings in Ocaml?

You can compare strings with the usal comparison operators: = , <> , < , <= , > , >= . You can also use the compare function, which returns -1 if the first string is less than the second, 1 if the first string is greater than the second, and 0 if they are equal.

How do I combine two strings in Ocaml?

The (^) binary operator concatenates two strings.


2 Answers

Use the function string_of_int (see the documentation for Pervasives, the module containing the functions that are automatically made available in the top level namespace to al OCaml programs).

like image 149
Michael Ekstrand Avatar answered Oct 10 '22 18:10

Michael Ekstrand


Another solution is to use the module Printf, which allows you to choose the format of printing:

Printf.sprintf "%d" 42 

gives you "42".

But you might prefer using an octal, hexadecimal, binary, etc representation. For instance,

Printf.sprintf "%x" 42 

gives you "2a" which is the hexadecimal representation of 42.

Printf.sprintf "0x%x" 42 

would give you "0x2a".

See the Printf documentation for more details.

like image 31
esope Avatar answered Oct 10 '22 18:10

esope