如何在c#中从文件中读取文本从一个值到另一个值
c#
我是 C# 新手,我还在学习那门语言。现在我尝试制作读取文本和数据的应用程序,我只需要特定的行。文字看起来像:
[HAEDING]
Some value
[HEADING]
Some other value
[HEADING]
Some other text
and continuation of this text in new line
[HEADING]
Last text
我尝试编写读取文本并将其放入 string[] 的方法,方法如下:
string[0] = Some value
string[1] = Some other value
string[2] = Some other text and continuation of this text in new line
string[3] = Last text
所以我想从值 [HEADING] 读取行到空的值新行。我认为应该由 ReadAllLines 写入并逐行检查值 [HEADING] 的起始位置和新行中空值的结束位置。我试试这个代码:
string s = "mystring";
int start = s.IndexOf("[HEADING]");
int end = s.IndexOf("n", start);
string result = s.Substring(start, end - start);
但它是我文本中所有行的子字符串,而不是第一个 [HEADING] 和空的新行、第二个等之间的循环。也许有人可以帮我解决这个问题?
回答
您可以尝试拆分字符串"[HEADING]"以获取这些行之间的字符串。然后你可以将每个字符串连接成一行并修剪字符串周围的空格:
string content = @"[HEADING]
Some value
[HEADING]
Some other value
[HEADING]
Some other text
and continuation of this text in new line
[HEADING]
Last text";
var segments = content.Split(new[] { "[HEADING]"}, StringSplitOptions.RemoveEmptyEntries) // Split into multiple strings
.Select(p=>p.Replace("rn"," ").Replace("r"," ").Replace("n"," ").Trim()) // Join each single string into single line
.ToArray();
结果:
segments[0] = "Some value"
segments[1] = "Some other value"
segments[2] = "Some other text and continuation of this text in new line"
segments[3] = "Last text"