在文件中的特定字符后插入换行符

本文关键字:字符 插入 换行符 文件 | 更新日期: 2023-09-27 17:51:11

我想在从文本文件读取的C#中的特定字符后面插入一个换行符。我有一个类似的文本文件

string text = File.ReadAllText(@"T:'data.txt");

它包含一个非常大的单行文本(下面只是其中的一小部分(。

"dep-1" : "M579.01303,612.20699L578.77297,612.20699 L578.77297,611.967L579.01303 Z","dep-2" : "M579.01303,612.20699L578.77297,612.20699 L578.77297,611.967L579.01303 Z","dep-3" : "M579.01303,612.20699L578.77297,612.20699 L578.77297,611.967L579.01303 Z"

现在我需要在Z〃之后输入折线并保存文件。然后文本将格式化为:

"dep-1" : "M579.01303,612.20699L578.77297,612.20699 L578.77297,611.967L579.01303 Z",
"dep-2" : "M579.01303,612.20699L578.77297,612.20699 L578.77297,611.967L579.01303 Z",
"dep-3" : "M579.01303,612.20699L578.77297,612.20699 L578.77297,611.967L579.01303 Z"

这在C#中可能吗?

在文件中的特定字符后插入换行符

string[] lines = File.ReadAllLines(path);
for (int i = 0; i < lines.Length; i++)
     lines[i] = lines[i].Replace("Z'",", "Z'"," + Environment.NewLine);
File.WriteAllLines(lines, path);

基本思想是,你读取所有的行,然后你只需将Z"替换为Z"加上一个换行符。之后,将所有行写入同一位置。

好吧,这是我对所有文本都在同一行时的编辑,(该死的技巧问题(;

 string file = File.ReadAllText(path);
 file.Replace("Z'",", "Z'"," + Environment.NewLine);
 File.WriteAllText(path);

你可以试试这个:

string text = File.ReadAllText(@"T:'data.txt");
string newText = string.Join("Z'", 'r'n", 
            text.Split(new[] { "Z'"," }, StringSplitOptions.RemoveEmptyEntries));
File.WriteAllText("path", newText);

简单地写:

 text = text.Replace("Z", "Z'n");