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

查看:35
本文介绍了在文本文件中每一行的第 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

阅读这篇文章很有帮助:

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 读取所有行,然后简单地将您的字符添加到所需位置,如下代码所示:

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:	est	est.txt"; //input file
string path2 = @"E:	est	est2.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天全站免登陆