本文介绍了如何从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

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

但我想得到

推荐答案

对@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#中的字符串中提取十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 17:40