gpt4 book ai didi

c# - 解析指定字符串上的文件

转载 作者:行者123 更新时间:2023-11-30 23:05:13 25 4
gpt4 key购买 nike

我编写了下面的代码来解析具有以下格式的文件。

请告诉我是否可以清理该代码,最好是编写 lambda 表达式而不是 for 循环。

方法中的代码已经使用 StreamReader 类将文件内容保存在 StringBuilder 变量中。

格式

enter image description here

代码
来自调用函数的解析器等于“其他总计”

private void ParseObject(StringBuilder body, string parser)  
{
List<string> lines = body.ToString().Split(Convert.ToChar(Helper.newLine)).ToList();
List<string> pages = new List<string>();

body.Length = 0;

int counter = 0;
int startPosition = 0;

for (int i = startPosition; i < lines.Count; i++)
{
if (lines[i].Contains(parser))
{

counter = i + 1;
for (int j = startPosition; j < counter; j++)
{
if (!lines[j].Contains(Helper.lineFeed))
{
body.Append(string.Concat(lines[j], Helper.newLine));
}
}

startPosition = counter;
pages.Add(body.ToString());
body.Length = 0;
}
}
}

返回的字符串如下所示:
页[0]
enter image description here

页[1]

enter image description here

最佳答案

看来您可以只使用 IndexOf 的重载,它采用先前的起始位置来遍历字符串,在“Other Total:”字符串之后的第一个换行符处将其拆分。

private List<string> ParseObject(StringBuilder body, string parser)
{
List<string> pages = new List<string>();

string data = body.ToString();
int splitPos = 0;
int startPos = 0;
while (true)
{
// Search the position of the parser string starting from the
// previous found pos
int parserPos = data.IndexOf(parser, splitPos);
if (parserPos != -1)
{
// Now we search the position of the newline after the
// found parser pos
splitPos = data.IndexOf(Environment.NewLine, parserPos);

// Take the substring starting from the previous position up to
// the current newline position
pages.Add(data.Substring(startPos, splitPos - startPos).Trim());

// reposition to the new starting position for IndexOf
startPos = splitPos;
}
else
break;
}
return pages;
}

然后你用

调用它
var result = ParseObject(input, "Other Total:");

注意你应该返回页面列表,否则调用是无用的

关于c# - 解析指定字符串上的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48936109/

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