我有一个文本文件,其中包含以下信息:
ALLOC
apple1
orange1
banana1
ALLOC
apple2
orange2
banana2
ALLOC
apple3
orange3
banana3基于stackflow社区的帮助,我现在能够读取整个文件。我还发现,要在标签之间提取内容,对于ex,ALLOC,我可以写:
var filelocation = @"c:\Fruits.txt";
var sectionLines = File.ReadAllLines(filelocation).TakeWhile(l => !l.StartsWith("ALLOC"));但这会给我IEnumerable<string>
apple1
orange1
banana1
apple2
orange2
banana2
apple3
orange3如何创建3个单独的字符串作为
string1 = apple1 orange1 banana1
string2 = apple2 ornage2 banana2
string3 = apple3 orange3简而言之,需要提取标签之间的内容。
发布于 2016-12-01 01:12:37
以下是一些可以返回所需结果的方法:
string[] words = { "ALLOC", "apple1", "orange1", "banana1", "ALLOC", "apple2", "orange2", "banana2", "ALLOC" };
var result = string.Join(" ", words)
.Split(new string[] { "ALLOC" }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Trim(' '));首先,我要把所有的字串起来。而不是用"ALLOC“来分割,然后选择被裁剪的字符串。
结果是:
string[] result = { "apple1 orange1 banana1", "apple2 orange2 banana2" };为你的案子,
var filelocation = @"c:\Fruits.txt";
var allLines = File.ReadAllLines(filelocation);
var sectionLines = string.Join(" ", allLines)
.Split(new string[] { "ALLOC" }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Trim(' '));发布于 2016-12-01 01:42:16
这可能对你有好处
string fullstr = File.ReadAllText("c:\\Fruits.txt");
string[] parts = fullstr.Split(new string[] { "ALLOC" }, StringSplitOptions.RemoveEmptyEntries);
List<string> outputstr = new List<string>();
foreach(string p in parts)
{
outputstr.Add(p.Replace("\r\n", " ").Trim(' '));
}在这里,我们使用File.ReadAllText一次读取所有文本,然后用ALLOC拆分它,然后在outputstr中通过用空格替换\r\n (新行)添加拆分的字符串,并对结果进行修剪。

https://stackoverflow.com/questions/40900881
复制相似问题