【问题标题】:How to loop through the whole text file?如何遍历整个文本文件?
【发布时间】:2015-10-04 19:32:10
【问题描述】:

我需要你的帮助!我正在编写一个脚本,该脚本从文本文件中获取字符串,该字符串从文本文件中获取 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();


            }
        }
    }
}

【问题讨论】:

  • 使用 ReadLine() 代替 ReadToEnd()。
  • 在你的例子中。为什么01253654758965475896后面加了空格,而另一行没有加类似的空格?
  • 感谢您的关注,我忘了添加空格,我更新了帖子。

标签: c# loops foreach


【解决方案1】:

如 cmets 中所述,首先将 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;

另一个问题是你只写第一行,因为你每次循环检查文件是否存在,如果文件存在你不写行。

以下是您的代码将如何处理此类更改(和其他更改):

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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多