使用linq解析文本

时间:2013-03-14 10:58:02

标签: c# string linq

我有这样的文字

      5       1     .021   -56.6   -5      0.4    -5      0.    
   -.05     -.1     .05     -.1     .05      .1    -.05      .1       
   YESA      1.                                                       
  .8507  .84993

我必须得到

      5       1     .021   -56.6   -5      0.4   -5      0.    
   -.05     -.1     .05     -.1     .05      .1    -.05      .1       
   YESA      1.     0.       0.      0.      0.      0.      0.               
  .8507  .84993     0.       0.      0.      0.      0.      0. 

但是当我使用下一个施工时

   FileStream fs = new FileStream(fileName, FileMode.Open);
            StreamReader sr = new StreamReader(fs);
         while (!sr.EndOfStream)
        {
            string line = sr.ReadLine();
            string temp = System.Text.RegularExpressions.Regex.Replace(line, @"\s+", " ");
            string[] vector = temp.Split(' ');
            for (int i = 0; i < vector.Length; i++)
                Console.WriteLine(ConvertToFloat(ConvertString(vector[i])));
        }

我得到的第一个文字没有变化。

2 个答案:

答案 0 :(得分:1)

我不明白为什么你甚至懒得解析花车。

看起来你只有一些项目(可能是浮动或不是浮动),你必须完成8个项目的行。像

        foreach (string line in lines)
        {
            var words = line.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            foreach(string w in words)
                Console.Write("{0,6}", w);

            // filling out
            for (int i = words.Length; i < 8; i++)
                Console.Write("{0,6}", "0.");

            Console.WriteLine();
        }

答案 1 :(得分:0)

我使用两个辅助功能

private float ConvertToFloat(string line)//to check integer or float number
        {
            string temp = "";

            if (line[line.Length - 1] == ',' || line[0] == ',')
            {
                temp = line.Replace(',', '\0');
                return float.Parse(temp);
            }
            else
                return float.Parse(line);

        }
        private string ConvertString(string line)//change '.' to ','
        {
            return line.Replace('.', ',');
        }