2015-10-04 171 views
0

我需要你的幫助!,我正在研究一個腳本,該腳本從一個文本文件中獲取字符串,該文本從20個文本文件中獲取一個值。如何遍歷整個文本文件?

現在我想在從文本文件中抓取的字符前添加空格。但是,我想將其應用於整個文本文件。

例如:

文本1 A(輸入):

01253654758965475896N12345 
012536547589654758960011223325 

(輸出):

(added 10 spaces in front)01253654758965475896 N12345 
(added 10 spaces in front)01253654758965475896 0011223325 

想法是循環通過它們,我增加10米的空間中前方然後在01253654758965475896之後也加上空格。

這是我的代碼:

class Program 
    { 
     [STAThread] 
     static void Main(string[] args) 
     { 

      int acc = 1; 
      string calcted = (acc++).ToString().PadLeft(20, '0'); 
      string ft_space = new string(' ', 12); 

      string path = Console.ReadLine(); 
      using (StreamReader sr = File.OpenText(path)) 
      { 
       string s = ""; 
       while ((s = sr.ReadToEnd()) != null) 
       { 

         string px = s; 
         string cnd = s.Substring(0, 16); 
         string cdr = cnd; 

         px = ft_space + cdr; 

         Console.Write("Enter Location:"); 
         string pt1 = Console.ReadLine(); 
         if (!File.Exists(pt1)) 
         { 

          using (TextWriter sw = File.CreateText(pt1)) 
          { 
           sw.Write(px); 
          } 

         } 
        } Console.ReadKey(); 


      } 
     } 
    } 
} 
+1

使用輸入行()()。 –

+0

在你的例子中。爲什麼在'01253654758965475896'之後添加空格,但是您沒有爲其他行添加類似的空格? –

+0

感謝您的關注,我忘了添加空格,我更新了帖子。 – Thisisyou

回答

1

如評論中所述,首先將ReadToEnd更改爲ReadLine

ReadToEnd將讀取所有文件,ReadLine將在每個循環迭代中讀取一行。

然後,由於您需要20個字符而不是16個字符,因此您需要將s.Substring(0, 16)更改爲s.Substring(0, 20)

之後,您需要獲取該行的其餘部分,以便將s.Substring(20)

然後,您需要將所有零件拼接在一起,就像這樣:

string result = spaces10 + first_part + spaces3 + second_part; 

另一個問題是,你只寫第一行是因爲你檢查文件是否存在環路每次和你不如果文件存在,則寫入該行。

這裏是你的代碼怎麼會這樣的變化(及其他)照顧:不是ReadToEnd的

string spaces10 = new string(' ', 10); 

string spaces3 = new string(' ', 3); 

string input_file = Console.ReadLine(); 
Console.Write("Enter Location:"); 
string output_file = Console.ReadLine(); 

using (StreamReader sr = File.OpenText(input_file)) 
{ 
    using (TextWriter sw = File.CreateText(output_file)) 
    { 
     string line; 
     while ((line = sr.ReadLine()) != null) 
     { 
      string first_part = line.Substring(0, 20); 

      string second_part = line.Substring(20); 

      string result = spaces10 + first_part + spaces3 + second_part; 

      sw.WriteLine(result); 

     } 
    } 
} 

Console.ReadKey(); 
+0

非常感謝!作品! – Thisisyou

+0

@Thisisyou:請將答案標記爲已接受,如果它適合您並且已完成。 – displayName