本文介绍了删除文本文件中每行第 n 个位置的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文件夹中有多个文本文件.我需要删除文本文件中每行的第 8 个字符处的字符.文本文件有 100+ 多行

I have multiple text files in folder. I need to delete character at the 8th character of each line in the text files. Text files have 100+ multiple rows

我将如何执行此操作?

原始文件示例:

123456789012345....
abcdefghijklmno....

新文件:

12345679012345
abcdefgijklmno

阅读这篇文章很有帮助:

Reading this article is helpful:

在字符串的每一行添加一个字符

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

Note: Length of text lines can be variable (not sure if it matters- one row can have 20 characters, next line may have 30 characters, etc.All text files are in folder: C:TestFolder

类似问题:在每行的第 n 个位置插入字符在文本文件中

推荐答案

您可以使用 File.ReadAllLines()string.Substring() 方法如下:

You can use File.ReadAllLines() and string.Substring() methods as follwing:

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, 7) + line.Substring(8) : line);
    }
    File.WriteAllText(file, sb.ToString()); //overwrite modified content
}

  • line.Substring(0, 7) 表示前 7 个字符(字符 #0 到 #6,长度为 7).
  • line.Substring(8) 表示从第 9 个字符到结尾(char #8 到结尾).
    • line.Substring(0, 7) means first 7 characters (char #0 to #6 with length of 7).
    • line.Substring(8) means from 9'th character to end (char #8 to end).
    • 请注意,字符位置是零索引的!

      Note that char positions are zero-indexed!

      这篇关于删除文本文件中每行第 n 个位置的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 05:22