我想用C#编写程序读取一个文件并以相反的顺序吐出另一个原始文件中包含所有单词的文件,并删除所有单词,如" a"和""。
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"和""。
答案 0 :(得分:5)
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
。