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

跟風遠走 提交于 2020-01-06 04:45:16

问题


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

How would I conduct this?

Original file example:

123456789012345....
abcdefghijklmno....

New file:

12345679012345
abcdefgijklmno

Reading this article is helpful:

Add a character on each line of a string

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

Similar question: Insert character at nth position for each line in a text file


回答1:


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) 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!



来源:https://stackoverflow.com/questions/55876966/delete-character-at-nth-position-for-each-line-in-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!