拆分字符串并转换为double

拆分字符串并转换为double

本文介绍了拆分字符串并转换为double值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用streamreader.File.readallLine()方法在c#中读取文件,每行包含三个浮点值。如何通过拆分字符串来提取每个浮点值?

下面给出了我的代码用于拆分字符串,但它没有正常工作!

i read file in c# using streamreader.File.readallLine() method and every line contains three float values.How to extract every float value by splitting string?
My code is given below for split string but it not working proporly!

try {

                var lines = File.ReadAllLines("InFIle.txt").Skip(1).ToList();
                for (int i = 0; i < lines.Count; i++)
                {
                    var line = lines[i];
                    var columns = line.Split('\n');
                }

            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }





以-610 \ t -701 \ t -701格式收到字符串,如何提取第二列和第三列值?



Received string in "-610\t -701\t -701" format,how to extract second and third column value?

推荐答案

try
           {

               var lines = File.ReadAllLines("InFIle.txt").Skip(1).ToList();
               for (int i = 0; i < lines.Count; i++)
               {
                   var line = lines[i];
                   var columns = line.Split('\n');
                   for (int columnsLoop = 0; columnsLoop < columns.Length; columnsLoop++)
                   {
                       string[] DecimalsArray = columns[columnsLoop].Split('\t');
                       decimal firstVal = Convert.ToDecimal(DecimalsArray[0]);
                       decimal secondVal = Convert.ToDecimal(DecimalsArray[1]);
                       decimal thirdVal = Convert.ToDecimal(DecimalsArray[2]);
                   }

               }

           }
           catch (Exception exc)
           {
               MessageBox.Show(exc.Message);
           }


// required
using System.Collections.Generic;
using System.Linq;

// inside your Class, Form, etc.
private string floatStr = @"-610	-701	-701
-607	-699	-699
-606	-697	-697
-604	-696	-696
-603	-696	-695
-603	-696	-695";

// split on tab character
private char[] splitChar = new char[] {'\t'};

// to hold result of split
private string[] stringAry;

// to hold list of float result
private List<float> floatList;

private void stringsToFloat (object sender, EventArgs e)
{
    // get rid of newline and linefeed
    floatStr = floatStr.Replace('\r', '\t');
    floatStr = floatStr.Replace('\n', '\t');

    // split
    stringAry = floatStr.Split(splitChar, StringSplitOptions.RemoveEmptyEntries);

    // use Linq to convert to List<float>
    floatList = stringAry.Select(float.Parse).ToList();
}</float>

调用此方法后,'floatStr将包含一个包含18个浮点值的List。



请注意,这里没有验证;如果其中一个字符串转换为浮点数的条目不正确会发生什么?

After this method is called, 'floatStr will contain a List of 18 float values.

Note that there's no validation here; what happens if there's an incorrect entry for one of the string to be converted to a float ?


这篇关于拆分字符串并转换为double值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:17