在为项目使用 F# 进行编码时,我想要将 char 转换为 int。即
let c = '3'
c |> int //this will however give the ascii value of 3 I believe
我的问题是,在 char 只包含数字的情况下,将单个 char 转换为 int 而不将 char 转换为字符串或其他类型的最佳方法是什么?
假设您已经验证了该字符并且知道它是一个 ASCII 数字,您可以执行以下操作:
let inline charToInt c = int c - int '0'
let c = '3'
c |> charToInt
注:如果您最终需要
float
而不是 int
,则有一个内置机制:System.Char.GetNumericValue
如果你想转换 a -> 0, b -> 1, ....., z -> 26。那么你可以这样做
let let2nat (letter : char) = int letter - int 'a'
如果你只想要ascii,你可以这样做
let let2ascii (let2ascii : char) = int let2ascii
几分钟前我遇到了同样的问题,但我用这两种方法解决了
int (string valueChar)
int (Char.GetNumericValue valueChar)
知道 valueChar 是“5”或类似值,并且您想要 int 值
先转换为字符串:
let toInt (c: char) = sprintf $"{c}" |> int
let c = '1'
let n1 = toInt c