可能重复:
在 C# 中从字符串中解析多个双精度浮点数
假设我有一行文本,如下所示:
"45.690 24.1023 .09223 4.1334"
在 C# 中,从这行文本中提取数字的最有效方法是什么?每个数字之间的空格数量因行而异,且无法预测。由于我需要执行此操作数千次,因此效率至关重要。
谢谢。
可能重复:
在 C# 中从字符串中解析多个双精度浮点数
假设我有一行文本,如下所示:
"45.690 24.1023 .09223 4.1334"
在 C# 中,从这行文本中提取数字的最有效方法是什么?每个数字之间的空格数量因行而异,且无法预测。由于我需要执行此操作数千次,因此效率至关重要。
谢谢。
IEnumerable<double> doubles = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select<string, double>(double.Parse)
已更新为使用StringSplitOptions.RemoveEmptyEntries,因为空格数量会有所不同
string input = "45.690 24.1023 .09223 4.1334";
string pattern = "\\s*"; // Split on whitepsace
string[] substrings = Regex.Split(input, pattern);
foreach (string match in substrings)
{
Console.WriteLine("'{0}'", match);
}
var chars = new List<char>();
for( int i =0; i < numChars; ++i )
if( char.IsDigit( text[i] ) )
chars.Add(text[i]);
You want efficient.....
var regex = new Regex(@"([\d\.]+)", RegexOptions.Compiled)
var matches = regex.Matches(input);