C#将小说 txt 按章节拆分
时间: 2023-07-12 21:14:01 浏览: 183
可以使用C#中的System.IO和System.Text命名空间来实现将小说txt按章节拆分的功能。
以下是一个简单的示例代码,可以将输入的小说txt文件按照章节拆分为多个单独的txt文件,并按照章节命名:
```csharp
using System;
using System.IO;
using System.Text;
namespace NovelSplitter
{
class Program
{
static void Main(string[] args)
{
// 输入小说txt文件路径
Console.Write("请输入小说txt文件路径:");
string filePath = Console.ReadLine();
// 读取小说txt文件内容
string novelText = File.ReadAllText(filePath, Encoding.UTF8);
// 按章节拆分并保存为单独的txt文件
string[] chapters = novelText.Split(new string[] { "第" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 1; i < chapters.Length; i++)
{
string chapterText = chapters[i];
int endIndex = chapterText.IndexOf("章");
string chapterTitle = "第" + chapterText.Substring(0, endIndex) + "章";
chapterText = chapterText.Substring(endIndex + 1);
// 将章节文本保存到单独的txt文件中
string chapterFilePath = Path.Combine(Path.GetDirectoryName(filePath), chapterTitle + ".txt");
File.WriteAllText(chapterFilePath, chapterText, Encoding.UTF8);
}
Console.WriteLine("小说已按章节拆分并保存为单独的txt文件。");
Console.ReadLine();
}
}
}
```
使用方法:
1. 将上述代码保存为NovelSplitter.cs文件;
2. 使用Visual Studio或其他C#编译器编译NovelSplitter.cs文件,生成可执行文件NovelSplitter.exe;
3. 打开命令行终端,进入NovelSplitter.exe所在目录;
4. 运行NovelSplitter.exe,按照提示输入小说txt文件路径;
5. 程序将会按照章节拆分小说txt文件,并将各章节保存为单独的txt文件,保存在原小说txt文件所在目录中。