替换文本文档中的找到的行

时间:2016-09-05 13:08:49

标签: c#

我得到了这个代码,它找到带有奇数索引的双精度来替换所有的“X”,除了第一个带有奇数索引但是保持所有双精度数均匀的索引。问题是如何替换文本文档中的找到的行。这样我得到的结果必须被替换但是如何覆盖文本文档中的行

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = "test.txt";
        static void Main(string[] args)
        {
            List<string> uniqueOddLines = new List<string>();
            List<string> lines = new List<string>();
            string inputLine = "X";
            StreamReader reader = new StreamReader(FILENAME);
            int index = 0;
            while ((inputLine = reader.ReadLine()) != null)
            {
                inputLine = inputLine.Trim();
                if (++index % 2 == 0)
                {
                    lines.Add(inputLine);
                }
                else
                {
                    if (uniqueOddLines.Contains(inputLine))
                    {
                        lines.Add(string.Format("Rewrite line {0}", index));
                    }
                    else
                    {
                        uniqueOddLines.Add(inputLine);
                        lines.Add(inputLine);
                    }
                }    
            }   
            foreach (string line in lines)
            {
                Console.WriteLine(line);
            }
            Console.ReadLine();
        }
    }
}

例如,文本文档中的内容是:

row1
row2
row3 
row4
row5
row6
row3 
row8
row9
row3 
row11 
row3 
row3 
row3 

给定代码的工作:

01. row1
02. row2
03. row3 <- keep row with odd index because it is first in order  
04. row4
05. row5
06. row6
07. row3 <- rewrite this double because it is not the first one with odd index
08. row8
09. row9
10. row3 <- keep this double, because row index is even number 
11. row11 
12. row3 <- keep this double, because row index is even number 
13. row3 <- rewrite this double because it is not the first one with odd index
14. row3 <- keep this double, because row index is even number

这是理想的结果,与上面相同,但我希望它在文本文档中:

row1
row2
row3 
row4
row5
row6
X
row8
row9
row3 
row11 
row3 
X
row3 

1 个答案:

答案 0 :(得分:0)

我建议使用 Linq ReadLines将返回文件行,Select便于在其中实现逻辑:

const string FILENAME = "test.txt";

// Side effect (adding into the set while selecting) is very convenient in the context,
// but should be implemented with care 
HashSet<String> appeared = new HashSet<String>();

var result = File
  .ReadLines(FILENAME)
   // index % 2 == 0 since index is zero-based
  .Select((line, index) => !appeared.Add(line.Trim()) && (index % 2 == 0) 
     ? "X"
     : line)
  .ToList(); // materialization, in case you want both Console and File 

foreach (var line in result)
  Console.WriteLine(line);

Console.ReadLine();

如果您想将这些行写回文件以及控制台:

File.WriteAllLines(FILENAME, result);