gpt4 book ai didi

F# - 将 char 转换为 int

转载 作者:行者123 更新时间:2023-12-04 05:36:41 27 4
gpt4 key购买 nike

在 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

Online Demo

备注如果您最终需要一个 float而不是 int有一个内置机制: System.Char.GetNumericValue

关于F# - 将 char 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42820232/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com