在文本文件中每行的第n个位置插入字符 [英] Insert character at nth position for each line in a text file

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

问题描述

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

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

我将如何进行?

原始文件示例:

123456789012345....
abcdefghijklmno....

新文件:

12345678 9012345
abcdefgh ijklmno

阅读本文很有帮助:

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

注意:文本行的长度可以变化(不确定是否重要,一行可以包含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读取所有行,并只需将您的char添加到所需位置,如以下代码所示:

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)

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

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
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆