删除文本文件中每行第n个位置的字符 [英] Delete character at nth position for each line in a text file
问题描述
我的文件夹中有多个文本文件。我需要删除文本文件中每行第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
阅读本文很有帮助:
注:文本行的长度可以变化(不确定是否重要-一行可以包含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个位置插入字符
推荐答案
Y您可以将 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个字符到末尾(字符#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).
请注意,char位置为零索引!
Note that char positions are zero-indexed!
这篇关于删除文本文件中每行第n个位置的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!