gpt4 book ai didi

c# - 使用 List 动态写入文件 : formatting issue

转载 作者:太空宇宙 更新时间:2023-11-03 22:43:58 25 4
gpt4 key购买 nike

我已经编写了一个函数,它可以让我动态地编写一个包含一些代码的文件。我正在为方法提供点数。我已经搞定了,但是我遇到了一个愚蠢的格式问题。

以下代码(numberOfPoints = 3)

private static void PointsGenerator(int numberOfPoints)
{
string fileContent = Resources.Points_AutoGenerated;
List<string> lines = new List<string>(fileContent.Split(new[] { Environment.NewLine }, StringSplitOptions.None));

for (var j = 0; j < numberOfPoints - 1; j++)
{
int index = 0;

for (var i = 1; !lines[i].Equals("ENDMODULE"); i++)
{
if (lines[i].Contains("! <<< POINT PLACEHOLDER >>>"))
{
if (numberOfPoints == 1)
{
// Let's remove the placeholder...
lines.RemoveAt(i);

// ... and the extra new-line.
lines.RemoveAt(i);
}
else
{
lines.RemoveAt(i);
lines.Insert(i, Resources.Snippet_POINT);
index = i;
}
}
}

if (j < numberOfPoints - 2)
{
lines.Insert(index + 2, "! <<< POINT PLACEHOLDER >>>");
}
}

Console.WriteLine(string.Join(Environment.NewLine, lines.ToArray()));
}

正在输出这个文件

! <<< Code generated with MG ABB Missions Generator. >>>

MODULE Points_AutoGenerated

TASK PERS robtarget pPointX := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];

TASK PERS robtarget pPointY := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];

TASK PERS robtarget pPointY := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];
ENDMODULE

我不喜欢它,因为我在 ENDMODULE 行之前缺少一个额外的换行符。

但是如果我使用第二个代码(只是粘贴我更改的部分)

if (j < numberOfPoints - 2)
{
lines.Insert(index + 2, "! <<< POINT PLACEHOLDER >>>");
}
else
{
lines.Insert(index + 1, Environment.NewLine);
}

我得到的是这个输出

! <<< Code generated with MG ABB Missions Generator. >>>

MODULE Points_AutoGenerated

TASK PERS robtarget pPointX := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];

TASK PERS robtarget pPointY := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];

TASK PERS robtarget pPointY := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];


ENDMODULE

和以前一样,我不喜欢它,因为末尾有额外的换行符(我只想要其中之一!)。

我错过了什么?

这是我用来生成最终文件的两个模板:

Points_AutoGenerated.txt

! <<< Code generated with MG ABB Missions Generator. >>>

MODULE Points_AutoGenerated

TASK PERS robtarget pPointX := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];

! <<< POINT PLACEHOLDER >>>

ENDMODULE

Snippet_POINT.txt

    TASK PERS robtarget pPointY := [[0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0], [9E9, 9E9, 9E9, 9E9, 9E9, 9E9]];

最佳答案

只需添加一个空字符串,您就已经从 WriteLine(Join()) 中获得了一个换行符。

else
{
lines.Insert(index + 1, "");
}

// here the empty string becomes an empty line
Console.WriteLine(string.Join(Environment.NewLine, lines.ToArray()));

关于c# - 使用 List<string> 动态写入文件 : formatting issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50873102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com