2013-03-26 13 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」變量包含了你想要的結果的文本文件。