【问题标题】:Insert character at nth position for each line in a text file在文本文件中的每一行的第 n 个位置插入字符
【发布时间】:2019-04-27 03:13:08
【问题描述】:

我有文本文件,我需要在文本文件的每一行的第 8 个字符处添加一个空格。文本文件有 1000+ 多行

我将如何进行?

原始文件示例:

123456789012345....
abcdefghijklmno....

新文件:

12345678 9012345
abcdefgh ijklmno

阅读这篇文章很有帮助:

Add a character on each line of a string

注意:文本行的长度是可变的(不确定是否重要,一行可以有 20 个字符,下一行可以有 30 个字符等。所有文本文件都在文件夹中:C:\TestFolder

类似的问题:

Delete character at nth position for each line in a text file

【问题讨论】:

    标签: c# regex text .net-core asp.net-core-2.0


    【解决方案1】:

    您不需要在这里使用正则表达式。一种简单的方法是使用File.ReadAllLines 读取所有行,然后将字符添加到所需位置,如下代码所示:

    var sb = new StringBuilder();
    string path = @"E:\test\test.txt"; //input file
    string path2 = @"E:\test\test2.txt"; //the output file, could be same as input path to overwrite
    string charToInsert = " ";
    string[] lines = File.ReadAllLines(path);
    foreach (string line in lines)
    {
        sb.AppendLine(line.Length > 8 ? line.Substring(0, 8) + charToInsert + line.Substring(9) : line);
    }
    File.WriteAllText(path2, sb.ToString());
    

    这里我使用不同的输出路径进行测试(不要覆盖输入)

    编辑:

    循环遍历文件夹中所有.txt文件的修改代码:

    string path = @"C:\TestFolder";
    string charToInsert = " ";
    string[] allFiles = Directory.GetFiles(path, "*.txt", SearchOption.TopDirectoryOnly); //Directory.EnumerateFiles
    foreach (string file in allFiles)
    {
        var sb = new StringBuilder();
        string[] lines = File.ReadAllLines(file); //input file
        foreach (string line in lines)
        {
            sb.AppendLine(line.Length > 8 ? line.Substring(0, 8) + charToInsert + line.Substring(9) : line);
        }
        File.WriteAllText(file, sb.ToString()); //overwrite modified content
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 2017-04-17
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多