创建152个字符的行,并在单词的末端调整线结尾
我正在尝试为自己编写一个小实用程序类来对文本进行一些格式化,以便每行的长度尽可能接近 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 语句来检查下一个字符是否是空格,如果不是,则读取和写入该字符。当看到下一个字符是空格时,内部 while 语句应该停止,然后写入行结束语句。
在读者和作者浏览完整个文档后,我将它们都关闭,并且应该有一个新文档,其中所有行的长度约为 152 个字符,并以单词结尾处结束。
显然这并没有像我预期的那样工作,这就是我提出问题的原因。由于 for 语句有效,因此我的嵌套 while 语句中有问题(可能是条件?),并且我不会无错误地退出程序。
任何建议将不胜感激。提前致谢。
I am trying to write a little utility class for myself to do some formatting of text so that each line is as close as possible to 152 characters in length. I have written this code:
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();
The for statement works fine. It reads and writes 152 characters without flaw. However, there is no guarantee that 152 characters will fall at the end of a word. So I wrote the nested while statement to check if the next character is a space, and if not, to read and write that character. The inner while statement is supposed to stop when it sees that the next character is a space, and then write in the line end statement.
After the reader and writer have gone through the entire document, I close them both and should have a new document where all the lines are approximately 152 characters long and end at the end of a word.
Obviously this isn't working as I anticipated and that is the reason for my question. Since the for statement works, there is something wrong in my nested while statement (perhaps the condition?) and I am not exiting the program without errors.
Any advice would be appreciated. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的文件测试结束是不正确的,
您的意思
是根据文档
注意在施放之前
Your end of file test is incorrect
you mean
as per docs
Note before casting
我可以建议如下内容吗?
Might I suggest something like the following.