如何从C#中的字符串中提取十进制数 [英] How to extract decimal number from string in C#

查看:31
本文介绍了如何从C#中的字符串中提取十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

对于此代码,我在digits数组中获得了这些值

For this code I get these values in the digits array

10,20,40,1

10,20,40,1

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

对于此代码,我在digits数组中获得了这些值

For this code I get these values in the digits array

10,4,20,5,40,1

10,4,20,5,40,1

但我想得到

10.4,20.5,40,1作为十进制数字.我该如何实现?

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

推荐答案

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

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() != "");

返回:

10.4
20.5
40
1

原始解决方案正在返回

[empty line here]
10.4
20.5
40
1
.

这篇关于如何从C#中的字符串中提取十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆