如何使streamwriter在特定数量的整数之后换行?

问题描述 投票:0回答:1

我有一个带有1000个随机数(长10个字符)的数字的文件,我想创建一个新的txt文件,该文件将在行中包含10个这些数字,然后再用另外10个数字换行。

我只能将它们全部打印在第一行上,或者每隔(10)个数字后再排一行。

        {
            string path = @"textasd.txt";
            string ro = @"nums.dat";
            StreamWriter sw = new StreamWriter(path);
            StreamReader sr = new StreamReader(ro);
            int length = 0,c;
            char[] field= new char[10];
            while ((c = sr.Read()) != -1)
            {
                if (char.IsDigit((char)c))
                {
                    pole[length] = (char)c;
                    length++;
                }
                else
                {
                    if(length >= 5)
                    {
                        sw.WriteLine(field, 0, length);
                    }
                    length = 0;
                }
            }
            sr.Close();
            sw.Close();
        }
c# streamreader streamwriter
1个回答
1
投票

Writeline总是写入新行。当已经写入10个数字时,您需要使用Write并具有一个WriteLine

{
    string path = @"textasd.txt";
    string ro = @"nums.dat";
    StreamWriter sw = new StreamWriter(path);
    StreamReader sr = new StreamReader(ro);
    int length = 0,c;
    char[] field= new char[10];
    var numbersProcessed = 0;  //----> this is new
    while ((c = sr.Read()) != -1)
    {
        if (char.IsDigit((char)c))
        {
            field[length] = (char)c;
            length++;
        }
        else
        {
            if(length >= 5)
            {
                //---> new code starts
                numbersProcessed++;
                sw.Write(field, 0, length);
                if (numbersProcessed % 10 == 0)
                {
                     sw.WriteLine();
                }
                //---> new code ends
            }
            length = 0;
        }
    }
    sr.Close();
    sw.Close();
}
© www.soinside.com 2019 - 2024. All rights reserved.