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

做~自己de王妃 提交于 2019-12-08 07:53:09

问题


I have text files, I need to add a space at the 8th character of each line in the text file. Text files have 1000+ multiple rows

How would I conduct this?

Original file example:

123456789012345....
abcdefghijklmno....

New file:

12345678 9012345
abcdefgh ijklmno

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:

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


回答1:


You don't need to use Regular Expressions here. One simple way is to use File.ReadAllLines to read all lines and simply add your char at desired position as in following code:

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());

Here I use a different path for output for test purposes (don't overwrite the input)

EDIT:

The modified code to loop through all .txt files in a folder:

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
}


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

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