拆分字符串然后解析为十进制
Split String and then parse as decimal
我有以下文字:
3.024 2.184 5.0000
在字符串变量中
然后我将其拆分并尝试解析十进制数,这是我的代码:
string linea;
linea = " 3.024 2.184 5.0000";
string[] test = linea.Split(' ');
Decimal[] numbers = Array.ConvertAll(test, decimal.Parse);
现在,当我进行解析时,出现此错误:
Input string was not in a correct format.
知道为什么会这样吗?
不确定您使用的是哪种语言,它是否支持正则表达式拆分?
linea.Split('\s+');
更新
自从学了C#之后,我就补上附加信息
string[] test = Regex.Split(linea, @"\s+");
https://msdn.microsoft.com/en-us/library/8yttk7sy(v=vs.110).aspx
为空的“”值添加一个捕获,当你去解析时跳过它们。虽然,消除它们可能更可取,在这种情况下(假设它不是值之间 spaces 的固定数量)递归地用 space 替换每个双 space 直到没有在 'linea'.
中加倍 spaces
在@neouser99 和评论的引导下,我想到了这个
string linea;
linea = " 3.024 2.184 5.0000";
string[] test = Regex.Replace(linea.Trim(), @"\s+", ",").Split(',');
Decimal[] numbers = Array.ConvertAll(test, decimal.Parse);
我有以下文字:
3.024 2.184 5.0000
在字符串变量中
然后我将其拆分并尝试解析十进制数,这是我的代码:
string linea;
linea = " 3.024 2.184 5.0000";
string[] test = linea.Split(' ');
Decimal[] numbers = Array.ConvertAll(test, decimal.Parse);
现在,当我进行解析时,出现此错误:
Input string was not in a correct format.
知道为什么会这样吗?
不确定您使用的是哪种语言,它是否支持正则表达式拆分?
linea.Split('\s+');
更新
自从学了C#之后,我就补上附加信息
string[] test = Regex.Split(linea, @"\s+");
https://msdn.microsoft.com/en-us/library/8yttk7sy(v=vs.110).aspx
为空的“”值添加一个捕获,当你去解析时跳过它们。虽然,消除它们可能更可取,在这种情况下(假设它不是值之间 spaces 的固定数量)递归地用 space 替换每个双 space 直到没有在 'linea'.
中加倍 spaces在@neouser99 和评论的引导下,我想到了这个
string linea;
linea = " 3.024 2.184 5.0000";
string[] test = Regex.Replace(linea.Trim(), @"\s+", ",").Split(',');
Decimal[] numbers = Array.ConvertAll(test, decimal.Parse);