【问题标题】:Read file and write in another file in reverse order with "a" and "the" stripped off读取文件并以相反的顺序写入另一个文件,去掉“a”和“the”
【发布时间】:2015-01-26 01:39:08
【问题描述】:

我想使用 C# 编写一个程序,读取一个文件并吐出另一个文件,该文件以相反的顺序包含原始文件中的所有单词,并去除了“a”和“the”等所有单词。

using (FileStream stream = File.OpenRead("C:\\file1.txt"))
using (FileStream writeStream = File.OpenWrite("D:\\file2.txt"))
{
    BinaryReader reader = new BinaryReader(stream);
    BinaryWriter writer = new BinaryWriter(writeStream);

    // create a buffer to hold the bytes 
    byte[] buffer = new Byte[1024];
    int bytesRead;

    // while the read method returns bytes
    // keep writing them to the output stream
    while ((bytesRead =
            stream.Read(buffer, 0, 1024)) > 0)
    {
        writeStream.Write(buffer, 0, bytesRead);
    }
}

我已经实现了之前的代码。如何反转并吐出字符“a”和“the”。

【问题讨论】:

  • 我会使用 StreamReader 和 StreamWriter 类。

标签: c# streamreader filereader memory-mapped-files


【解决方案1】:

File 有处理读取和写入文本的静态助手 - 对于大多数文本有点小的实际情况来说应该足够了:

File.WriteAllText(destinationFilePath,
String.Join(" ",
  File.ReadAllText(sourceFilePath)
   .Split(' ')
   .Where(s=> s != "a" && s != "the").Reverse())
);

如果您的来源包含句子而不仅仅是由空格分隔的单词 - 使用正则表达式来标记文本 - Regex split string but keep separators 而不是 String.Split

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-23
    • 2015-11-09
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 2023-04-05
    • 2018-07-06
    相关资源
    最近更新 更多