2013-03-26 38 views
2

我有这样的文字分析文本,并保存在内存中的C#

5  1  5  1  5  1  5  1  
     1 

我得

5  1  5  1  5  1  5  1  
0  1  0  0  0  0  0  0 

,并将其保存在内存中。但是,当我使用这样的建设:

List<string> lines=File.ReadLines(fileName); 
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(); 
     } 

我只打印所需的格式显示文本。 如何将它保存在List<string> newLines

+0

所以你想保存你的输出,因为它是在字符串列表中? – Shaharyar 2013-03-26 08:12:05

+4

如果你使用'RemoveEmptyEntries',你怎么知道第二行'1'的位置是?坦率地说,解析,我根本不认为'Split'是正确的选择 – 2013-03-26 08:12:17

+0

我没有把答案作为不确定,如果它是你想要的,而是(或者)'Console.Write',你可以使用'newLines.Add(string)' – Sayse 2013-03-26 08:12:27

回答

2

如果我们假设数据是指相等间隔(由当前Write等的建议,那么我会处理它作为字符

char[] chars = new char[49]; 
foreach(string line in File.ReadLines(path)) 
{ 
    // copy in the data and pad with spaces 
    line.CopyTo(0, chars, 0, Math.Min(line.Length,chars.Length)); 
    for (int i = line.Length; i < chars.Length; i++) 
     chars[i] = ' '; 
    // check every 6th character - if space replace with zero 
    for (int i = 1; i < chars.Length; i += 6) if (chars[i] == ' ') 
     chars[i] = '0'; 
    Console.WriteLine(chars); 
} 

或者,如果你真的需要它为线,使用(在每个循环迭代结束):

list.Add(new string(chars)); 
0

我假设有数字之间整整5空间,因此这里是代码:

List<string> lines = System.IO.File.ReadLines(fileName).ToList(); 
List<string> output = new List<string>(); 

foreach (string line in lines) 
{ 
    var words = 
     line.Split(new string[] { new string(' ', 5) }, 
        StringSplitOptions.None).Select(input => input.Trim()).ToArray(); 

    Array.Resize(ref words, 8); 

    words = words.Select(
       input => string.IsNullOrEmpty(input) ? " " : input).ToArray(); 

    output.Add(string.Join(new string(' ', 5), words)); 
} 

//output: 
// 5  1  5  1  5  1  5  1  
// 0  1  0  0  0  0  0  0 
0

您可以使用此代码用于生产所需的结果:

StreamReader sr = new StreamReader("test.txt"); 
      string s; 
      string resultText = ""; 
      while ((s = sr.ReadLine()) != null) 
      { 
       string text = s; 
       string[] splitedText = text.Split('\t'); 
       for (int i = 0; i < splitedText.Length; i++) 
       { 
        if (splitedText[i] == "") 
        { 
         resultText += "0 \t"; 
        } 
        else 
        { 
         resultText += splitedText[i] + " \t"; 
        } 
       } 
       resultText += "\n"; 
      } 
      Console.WriteLine(resultText); 

“的test.txt”是包含文本和“resultText”变量包含了你想要的结果的文本文件。