使用C#将文本附加到平面文件的每一行末尾

本文关键字:一行 文本 平面文件 使用 | 更新日期: 2023-09-27 17:59:04

如何使用c#将文本附加到平面文件中的行末尾?基本上,我想在每一行的末尾加上行号。

使用C#将文本附加到平面文件的每一行末尾

只是MasterXD解决方案的快速重构:

var linesInText = stringWithText.Split(Environment.NewLine);
StringBuilder stringWithRowNumbers = new StringBuilder();
var row = 1;
foreach (var line in linesInText)
{
    stringWithRowNumbers.Append(line);
    stringWithRowNumbers.Append(row++);
    stringWithRowNumbers.Append(Environment.NewLine);
}
string result = stringWithRowNumbers.ToString();

为此,使用StringBuilder将比简单的字符串串联执行得更好,并且在本用例中被认为是最佳实践。

这里有一个使用Linq的Enumerable.Select和String.Join方法(String,String[])以重新生成行。

string path = "Path to your flat file";
var numberedText = String.Join(Environment.NewLine, File.ReadAllLines(path).Select((line, index) => string.Join(" ", line.Trim(), index + 1)));
Console.WriteLine(numberedText);

生成的字符串在每行的末尾都有行号。

我想你说的平面文件是指普通的文本文件?

首先,你想把一段文本分成几行。这是通过以下方式实现的:

string[] linesInText = stringWithText.Split(''n');

字符'n表示一条新行。所以,每当出现一条"新线"时,就在那里分开。函数Split将字符串分成多个部分,其中分隔符作为输入。然后,这些部件将被制成一个字符串数组。在这种情况下,文本或字符串中的所有行都将变成一个数组。

现在,您需要将数字添加到每行的末尾。这可以通过以下方式实现:

string stringWithRowNumbers = "";
for (int i = 0; i < linesInText.Length; i++) // Go through all lines
{
    stringWithRowNumbers = linesInText[i] + "YourNumbers" + "'n"; // The old/first line + your numbers + new line
}

现在,您应该有一个字符串,所有行的末尾都有数字。

我希望这能有所帮助。

编辑:我刚意识到你要的是行号。这是正确的代码。

string stringWithRowNumbers = "";
for (int i = 0; i < linesInText.Length; i++) // Go through all lines
{
    // The space is intentional. If there is no space, then the number will not have any space between itself and the line
    stringWithRowNumbers = linesInText[i] + " " + (i + 1) + "'n"; // The old/first line + row number + new line
}