如何从字符串在C#中提取十进制数 [英] how do extract decimal number from string in c#
本文介绍了如何从字符串在C#中提取十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
string sentence = "X10 cats, Y20 dogs, 40 fish and 1 programmer.";
string[] digits = Regex.Split (sentence, @"\D+");
这段代码我得到的数字数组值这样10,20,40,1
for this code i get values in digits array like this 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
for this code i get values in digits array like this 10,4,20,5,40,1
但我喜欢得到这样10.4,20.5,40,1十进制数我怎样才能做到这一点。
but i like to get like this 10.4,20.5,40,1 in decimal numbers how can i do this.
推荐答案
小的改进,以@迈克尔的解决方案:
Small improvement to @Michael's solution:
// 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() != "");
返回:
Returns:
10.4
20.5
40
1
原来的溶液回
[empty line here]
10.4
20.5
40
1
.
这篇关于如何从字符串在C#中提取十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文