如何重写双精度只有奇数索引,除了最上面的行奇数和保持所有双精度偶数索引

本文关键字:索引 双精度 何重写 重写 | 更新日期: 2023-09-27 18:05:33

如何重写我的文本文档中所有重复的行,但只有当重复的行有奇数索引号,只保留一个奇数在所有的顺序之上,并保持所有重复的偶数索引。

例如:

01. line1
02. line2
03. line3    <-- keep this with odd index because it is first in order  
04. line4
05. line5
06. line6
07. line3    <-- rewrite this double because it is not first with odd index
08. line8
09. line9
10. line3    <-- keep this double, because line  index is even number 
11. line11 
12. line3    <-- keep this double, because line  index is even number 
13. line3    <-- rewrite this double
14. line3    <-- keep this double, because line  index is even number

如何重写双精度只有奇数索引,除了最上面的行奇数和保持所有双精度偶数索引

在我看来,您在编写逻辑上寻求帮助,而不是读写您的文件。因此,为了简单起见,我将假设一个数组作为输入,并使用索引代替行号来回答这个问题。

public void CleanFile(string[] lines) {
    var oddLines = new HashSet<String>();
    for(int i = 1; i <= lines.Length; i += 2) {
        if(!oddLines.Add(lines[i]) {
            lines[i] = //whatever your rewriting it with
        }
    }
}

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:'temp'test.txt";
        static void Main(string[] args)
        {
            List<string> uniqueOddLines = new List<string>();
            List<string> lines = new List<string>();
            string inputLine = "";
            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();
        }
    }
}