gpt4 book ai didi

c# - 字符串分数加倍

转载 作者:太空狗 更新时间:2023-10-29 17:42:23 24 4
gpt4 key购买 nike

我需要一个函数来将用户输入的数字解析为 double 。我不能在客户端做任何事情,也不能改变输入的方式。

Input       | Desired Output
"9" | 9
"9 3/4" | 9.75
" 9 1/ 2 " | 9.5
"9 .25" | 9.25
"9,000 1/3" | 9000.33
"1/4" | .25

我看到了这个post ,但它使用 Python,我只是想知道在我花时间编写自己的代码之前是否有人知道任何奇特的 C# 处理方法。

最佳答案

我会为此使用正则表达式:

Regex re = new Regex(@"^\s*(\d+)(\s*\.(\d*)|\s+(\d+)\s*/\s*(\d+))?\s*$");
string str = " 9 1/ 2 ";
Match m = re.Match(str);
double val = m.Groups[1].Success ? double.Parse(m.Groups[1].Value) : 0.0;

if(m.Groups[3].Success) {
val += double.Parse("0." + m.Groups[3].Value);
} else {
val += double.Parse(m.Groups[4].Value) / double.Parse(m.Groups[5].Value);
}

尚未测试,但我认为它应该可以工作。

Here's a demo , 和 here's another demo .

关于c# - 字符串分数加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8761531/

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