[英]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.