[英]F# - Convert a char to int
在 F# 中为项目编码时,我想将 char 转换为 int。 IE
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
先转换成字符串:
c |> sprintf "%c" |> int
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.