Home > database >  How to convert string with backslash to char
How to convert string with backslash to char

Time:10-10

I have to convert a backslash string into char, but it seems that casting doesn't exist like in java: String msg = (Char) new_msg

I have to convert string values like "\t", "\n", "\000"-"\255" to char.

CodePudding user response:

As an addendum to glennsl's answer, both methods will raise an Invalid_argument exception if the string is empty. If you were writing a function to get the first char of a string, you might use the option type to account for this.

let first_char_of_string s =
  try Some s.[0]
  with Invalid_argument _ -> None

CodePudding user response:

I would first start questioning why you have a single character string in the first place, and whether you can be sure that that is what you actually have. But given that it is, you can get a char from a string, whether it's in the first position or any other, using either String.get, or the more convenient string indexing operator:

let s = "\t"

let c: char = String.get s 0

let c: char = s.[0]

But note that these will both raise an Invalid_argument exception if there is no character at that position, such as if the string is empty, for example.

  • Related