Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当我找到匹配项时,从文件中提取三个字符串_C#_String_Concatenation - Fatal编程技术网

C# 当我找到匹配项时,从文件中提取三个字符串

C# 当我找到匹配项时,从文件中提取三个字符串,c#,string,concatenation,C#,String,Concatenation,我有一个应用程序,我在其中读取.txt文件的内容,如下所示: - ... - Nonsense - Nonsense - Nonsense - Line 1 - Line 2 - Line 3 - Nonsense - Nonsense - Line1 - Line2 - Line3 - Nonsense - ... etc 当我找到匹配的单词“Line1”时,我需要添加以下两行,以便得到以下结果 - Line1 Line2 Line3 - Line1 Line2 Line3 我使用st

我有一个应用程序,我在其中读取.txt文件的内容,如下所示:

- ...
- Nonsense
- Nonsense
- Nonsense
- Line 1
- Line 2
- Line 3
- Nonsense
- Nonsense
- Line1
- Line2
- Line3 
- Nonsense
- ... etc 
当我找到匹配的单词“Line1”时,我需要添加以下两行,以便得到以下结果

- Line1 Line2 Line3
- Line1 Line2 Line3
我使用streamreader和列表获取第一个值的行,但是合并下面两行的最佳实践是什么? 到目前为止,我的代码是:

List<string> match = new List<string>();
string line;        

using (StreamReader inputStream = new StreamReader(txtInput))
        {
            while ((line = inputStream.ReadLine()) != null)
            {
                if (line.Contains("Line1"))
                {
                    match.Add(line);                        
                }
            }
        }
列表匹配=新列表();
弦线;
使用(StreamReader inputStream=新的StreamReader(txtInput))
{
而((line=inputStream.ReadLine())!=null)
{
如果(第行包含(“第1行”))
{
匹配。添加(行);
}
}
}

我建议不要使用
StreamReader
。如果使用
File.ReadAllLines()
可以更轻松地遍历文本文件内容。您可以检查“Line1”之后是否有下面两行,这要简单得多

像这样的

var path = Path to the file;
List<string> lines = File.ReadAllLines(path).ToList();
List<string> matches = new List<string>();

for(int i = 0; i < lines.Count; i++)
{
    var line = lines[i];
    if(line.Equals("Line1"))
    {
        if (lines.Count > i + 2)
        {
            matches.Add(lines[i++]);
            matches.Add(lines[i++]);
            matches.Add(lines[i++]);
        }
    }
}
var path=文件的路径;
List lines=File.ReadAllLines(path.ToList();
列表匹配项=新列表();
对于(int i=0;ii+2)
{
匹配。添加(行[i++]);
匹配。添加(行[i++]);
匹配。添加(行[i++]);
}
}
}

我建议不要使用
StreamReader
。如果使用
File.ReadAllLines()
可以更轻松地遍历文本文件内容。您可以检查“Line1”之后是否有下面两行,这要简单得多

像这样的

var path = Path to the file;
List<string> lines = File.ReadAllLines(path).ToList();
List<string> matches = new List<string>();

for(int i = 0; i < lines.Count; i++)
{
    var line = lines[i];
    if(line.Equals("Line1"))
    {
        if (lines.Count > i + 2)
        {
            matches.Add(lines[i++]);
            matches.Add(lines[i++]);
            matches.Add(lines[i++]);
        }
    }
}
var path=文件的路径;
List lines=File.ReadAllLines(path.ToList();
列表匹配项=新列表();
对于(int i=0;ii+2)
{
匹配。添加(行[i++]);
匹配。添加(行[i++]);
匹配。添加(行[i++]);
}
}
}
使用C#7的本地函数语法(无论如何都不是必需的),您可以执行以下操作:

public IEnumerable<string> ProcessText(string txtInput)
{
    IEnumerable<string> GetNextNLines(IEnumerator<string> enumerator, int n)
    {
        var counter = 0;

        while (counter < n && enumerator.MoveNext())
        {
             yield return enumerator.Current;
             counter += 1;
        }

        if (counter != n) //consider throwing with an unexpected format message.
    }

    using (var enumerator = File.ReadLines(txtInput).GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            if (enumerator.Current.Constains("Line1"))
            {
                yield return enumerator.Current;

                foreach (var line in GetNextNLines(enumerator, 2)
                {
                    yield return line;
                }
            } 
        }
    }
}
public IEnumerable ProcessText(字符串txtInput)
{
IEnumerable GetNextLines(IEnumerator枚举器,int n)
{
var计数器=0;
while(计数器
这种方法是惰性的,可以避免预先读取整个文件,如果文件太大,可能会导致问题。

使用C#7的本地函数语法(无论如何都不是必需的),可以执行以下操作:

public IEnumerable<string> ProcessText(string txtInput)
{
    IEnumerable<string> GetNextNLines(IEnumerator<string> enumerator, int n)
    {
        var counter = 0;

        while (counter < n && enumerator.MoveNext())
        {
             yield return enumerator.Current;
             counter += 1;
        }

        if (counter != n) //consider throwing with an unexpected format message.
    }

    using (var enumerator = File.ReadLines(txtInput).GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            if (enumerator.Current.Constains("Line1"))
            {
                yield return enumerator.Current;

                foreach (var line in GetNextNLines(enumerator, 2)
                {
                    yield return line;
                }
            } 
        }
    }
}
public IEnumerable ProcessText(字符串txtInput)
{
IEnumerable GetNextLines(IEnumerator枚举器,int n)
{
var计数器=0;
while(计数器

这种方法很懒惰,可以避免预先读取整个文件,如果文件太大,可能会导致问题。

这样替换while循环可以解决问题

while ((line = inputStream.ReadLine()) != null)
                    {
                        string outputLine;
                        if (line.Contains("Line1"))
                        {

                            outputLine = line + inputStream.ReadLine() + inputStream.ReadLine();
                            match.Add(outputLine);
                        }

                    }

这样替换while循环将解决您的问题

while ((line = inputStream.ReadLine()) != null)
                    {
                        string outputLine;
                        if (line.Contains("Line1"))
                        {

                            outputLine = line + inputStream.ReadLine() + inputStream.ReadLine();
                            match.Add(outputLine);
                        }

                    }

如果您安装Microsoft的交互式框架(NuGet“System.Interactive”),那么您将获得一个名为
Buffer
的方便的
IEnumerable
扩展

List<string> match =
    File
        .ReadLines(txtInput)
        .Buffer(3, 1)
        .Where(x => x[0] == "Line1")
        .Select(x => String.Join(" ", x))
        .ToList();
列表匹配=
文件
.ReadLines(txtInput)
.缓冲区(3,1)
。其中(x=>x[0]==“第1行”)
.Select(x=>String.Join(“,x))
.ToList();

就这样。完成了。

如果您安装了Microsoft的交互式框架(NuGet“System.Interactive”),那么您将获得一个名为
Buffer
的方便的
IEnumerable
扩展。它将允许您执行以下操作:

List<string> match =
    File
        .ReadLines(txtInput)
        .Buffer(3, 1)
        .Where(x => x[0] == "Line1")
        .Select(x => String.Join(" ", x))
        .ToList();
列表匹配=
文件
.ReadLines(txtInput)
.缓冲区(3,1)
。其中(x=>x[0]==“第1行”)
.Select(x=>String.Join(“,x))
.ToList();

就这样。完成了。

如果我正确理解了您的要求,您需要一个串联字符串列表,每个字符串由3行串联而成,包括
第1行和下一行。要使用流读取器并稍微修改代码,请执行此操作:

 List<string> match = new List<string>();
 string line;

 using (StreamReader inputStream = new StreamReader(txtInput))
 {
     int charctersLeftAfterMatch = -1;
     string temp = "";
     while ((line = inputStream.ReadLine()) != null)
     {
         // If first instance is found, update characters to pick up next 2
         if (line.Contains("Line1") || line.Contains("Line 1"))
         {
              charctersLeftAfterMatch = 3;
              temp = "";
         }

         // If last line (3rd) has been reached then add to collection
         // Else if lines are still left then concatenate and move ahead
         if (charctersLeftAfterMatch-- == 1)
         {
              temp += line;
              match.Add(temp);
         }
         else if (charctersLeftAfterMatch > 0)
         {
              temp += line;
         }
     }
}

// Match contains 2 string's: 
// [0] Line 1 Line 2 Line 3
// [1] Line1 Line2 Line3
列表匹配=新列表();
弦线;
使用(StreamReader inputStream=新的StreamReader(txtInput))
{
int charactersLeftAfterMatch=-1;
字符串temp=“”;
而((line=inputStream.ReadLine())!=null)
{
//若找到第一个实例,则更新字符以拾取下一个2
如果(第1行(“第1行”)| |第1行(“第1行”))
{
CharactersLeftAfterMatch=3;
温度=”;
}
//如果已到达最后一行(第3行),则添加到集合中
//否则,如果行仍然保留,则连接并向前移动