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

How to make streamwriter make a new line after specific number of integers?

我有包含 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();
        }

Writeline 总是写入新行。您需要使用 Write 并在已写入 10 个数字时使用 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();
}