2015-10-04 144 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