创建 152 个字符的行并调整单词末尾的行尾

Creating lines of 152 characters and adjusting line endings at ends of words

我正在尝试为自己编写一个小实用程序 class 来对文本进行一些格式化,以便每行的长度尽可能接近 152 个字符。我写了这段代码:

StreamReader sr = new StreamReader("C:\Users\Owner\Videos\XSplit\Luke11\Luke11fromweb.txt");
StreamWriter sw = new StreamWriter("C:\Users\Owner\Videos\XSplit\Luke11\Luke11raw.txt");
int count = 152;
char chunk;
do
{
    for (int i = 0; i < count; i++)
    {
        chunk = (char)sr.Read();
        sw.Write(chunk);
    }

    while (Char.IsWhiteSpace((char)sr.Peek()) == false && (char)sr.Peek() > -1)
    {
        chunk = (char)sr.Read();
        sw.Write(chunk);
    }
    sw.WriteLine();
} while (sr.Peek() >= 0);

sr.Close();
sw.Close();

for 语句工作正常。读写152个字符无误。但是,不能保证 152 个字符会落在单词的末尾。所以我写了嵌套的 while 语句来检查下一个字符是否是 space,如果不是,则读取和写入该字符。当看到下一个字符是space时,内部while语句应该停止,然后在行结束语句中写入

在 reader 和作者完成整个文档后,我将它们都关闭,应该会有一个新文档,其中所有行的长度大约为 152 个字符,并在一个单词的末尾结束。

显然这没有像我预期的那样工作,这就是我提出问题的原因。由于 for 语句有效,我的嵌套 while 语句中有问题(也许是条件?)并且我没有在没有错误的情况下退出程序。

如有任何建议,我们将不胜感激。提前致谢。

您的文件结尾测试不正确

while (Char.IsWhiteSpace((char)sr.Peek()) == false && (char)sr.Peek() > -1)

你是说

while (Char.IsWhiteSpace((char)sr.Peek()) == false && sr.Peek() > -1)

根据文档

The Peek method returns an integer value in order to determine whether the end of the file, or another error has occurred. This allows a user to first check if the returned value is -1 before casting it to a Char type.

注意铸造前

我可以建议如下内容。

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        int maxLength = 152;
        string inputPath = @"c:\Users\Owner\Videos\XSplit\Luke11\Luke11fromweb.txt";
        string outputPath = @"c:\Users\Owner\Videos\XSplit\Luke11\Luke11raw.txt";
        try
        {
            if (File.Exists(outputPath))
            {
                File.Delete(outputPath);
            }

            using (StreamWriter sw = new StreamWriter(inputPath))
            {
                using (StreamReader sr = new StreamReader(outputPath))
                {
                    do
                    {
                        WriteMaxPlus(sr, sw, maxLength);
                    }
                    while (sr.Peek() >= 0);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }

    private static void WriteMaxPlus(StreamReader sr, StreamWriter sw, int maxLength)
    {
        for (int i = 0; i < maxLength; i++)
        {
            if (sr.Peek() >= 0)
            {
                sw.Write((char)sr.Read());
            }
        }

        while (sr.Peek() >= 0 && !Char.IsWhiteSpace((char)sr.Peek()))
        {
            sw.Write((char)sr.Read());
        }

        sw.WriteLine();
    }
}