简体   繁体   English

F# - 将 char 转换为 int

[英]F# - Convert a char to int

While coding in F# for a project, I have come to a point where I want to convert a char to an int.在 F# 中为项目编码时,我想将 char 转换为 int。 Ie IE

let c = '3'
c |> int //this will however give the ascii value of 3 I believe

My question is, what is the best way to convert a single char to an int without converting the char to a string or another types, in a case where the char only holds a digit?我的问题是,在 char 只包含一个数字的情况下,将单个 char 转换为 int 而不将 char 转换为字符串或其他类型的最佳方法是什么?

Assuming you've validated the character and know that it's an ASCII digit, you can do the following:假设您已经验证了该字符并知道它是一个 ASCII 数字,您可以执行以下操作:

let inline charToInt c = int c - int '0'

let c = '3'
c |> charToInt

Online Demo在线演示

Nb if you ultimately need a float rather than an int there is a built-in mechanism: System.Char.GetNumericValue注意,如果您最终需要float而不是int ,则有一个内置机制: System.Char.GetNumericValue

If you're trying to convert a -> 0, b -> 1, ....., z -> 26. Then you could do this如果你想转换 a -> 0, b -> 1, ....., z -> 26. 那么你可以这样做

let let2nat (letter : char) = int letter - int 'a'

If you just want the ascii you can do this如果你只想要 ascii 你可以这样做

let let2ascii (let2ascii : char) = int let2ascii

先转换成字符串:

c |> sprintf "%c" |> int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM