在文本文件中的现有文本中添加空格和字符

时间:2019-07-08 19:39:32

标签: c#

在运行初始代码后,我想通过编辑现有文本文件来改进程序。

当前代码:

private string file_path = @"Tags.txt";

public txtEditor()
{
    InitializeComponent();
}

//PROCEDURE
private void Procedure()
{
    // READ AND APPEND LINES
    File.WriteAllLines(file_path, File.ReadAllLines(file_path).Where(line => Regex.IsMatch(line, "NE 1:") || (Regex.IsMatch(line, "NE 2:"))));
}

private void btnRefine_Click(object sender, RoutedEventArgs e)
{
    Procedure();
}

运行代码的结果将文本文件更改如下:

LINE 1: hello
LINE 2: hello
LINE 1: hello
LINE 2: hello
LINE 1: hello
LINE 2: hello
  • 从这里开始,我想在现有文本中添加空格和尖括号,如下所示。
  • “ hello”一词是每个标签上不同的随机文本示例。
LINE 1: <hello
LINE 2: hello>

LINE 1: <hello
LINE 2: hello>

LINE 1: <hello
LINE 2: hello>

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

            var str = @"LINE 1: hello
LINE 2: hello
LINE 1: hello
LINE 2: hello
LINE 1: hello
LINE 2: hello";
        var arr = str.Split(new string[] { "\r\n" }, StringSplitOptions.None);
        string[] arr2 = new string[arr.Count()];
        bool pair = false;

        for (int i = 0; i < arr.Count(); i++)
        {
            if (pair)
            {
                var index = arr[i].Length;
                arr2[i] = arr[i].Insert(index, ">\r\n");
                pair = !pair;
            }
            else
            {
                arr2[i] = arr[i].Insert(8, "<");
                pair = !pair;
            }
        }
        string modString = "";
        foreach (var item in arr2)
        {
            modString += item + "\r\n";
        }
        MessageBox.Show(modString);