gpt4 book ai didi

c# - 如何从C#中的字符串中提取十进制数

转载 作者:可可西里 更新时间:2023-11-01 08:50:39 25 4
gpt4 key购买 nike

string sentence = "X10 cats, Y20 dogs, 40 fish and 1 programmer.";
string[] digits = Regex.Split (sentence, @"\D+");

对于这段代码,我在数字数组中获取了这些值

10,20,40,1

string sentence = "X10.4 cats, Y20.5 dogs, 40 fish and 1 programmer.";
string[] digits = Regex.Split (sentence, @"\D+");

对于这段代码,我在数字数组中获取了这些值

10,4,20,5,40,1

但我想得到喜欢

10.4,20.5,40,1as decimal numbers. How can I achieve this?

最佳答案

对@Michael 解决方案的小改进:

// NOTES: about the LINQ:
// .Where() == filters the IEnumerable (which the array is)
// (c=>...) is the lambda for dealing with each element of the array
// where c is an array element.
// .Trim() == trims all blank spaces at the start and end of the string
var doubleArray = Regex.Split(sentence, @"[^0-9\.]+")
.Where(c => c != "." && c.Trim() != "");

返回:

10.4
20.5
40
1

原来的解决方案正在返回

[empty line here]
10.4
20.5
40
1
.

关于c# - 如何从C#中的字符串中提取十进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3575331/

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