gpt4 book ai didi

c# - 如何删除文本文件中具有奇数索引行和下一个偶数字符串的重复字符串并避免出现偶数

转载 作者:行者123 更新时间:2023-12-01 23:15:47 26 4
gpt4 key购买 nike

我试图删除仅位于奇数索引号行上的重复字符串,并在文本文档中大约 30 000 行的下一个偶数行,并避免偶数行内容,只有当它是奇数之后的下一个时,才必须删除偶数复制。例如,索引号内容:

0. some text 1
1. some text 2
2. some text 3
3. some text 2
4. some text 5
5. some text 6
6. some text 2
7. some text 7
8. some text 2
9. some text 9

并且必须这样处理:

some text 1
some text 2 // keep unique
some text 3
some text 2 // remove odd duplicate
some text 5 // remove even because previous is odd duplicate
some text 6
some text 2 // keep because this duplicate on even line
some text 7
some text 2 // keep because this duplicate on even line
some text 9

要得到这个:

some text 1
some text 2
some text 3
some text 6
some text 2
some text 7
some text 2
some text 9

但我不知道如何得到这个结果。所以看来我必须阅读所有行内容,并要求索引:

if (index % 2 == 0)  
{

}

但无法得到,如何比较这些行以走得更远

最佳答案

样本:Simple | Extended

代码:

string[] lines = System.IO.File.ReadAllLines("/path/to/file.txt");
List<string> newLines = new List<string>();
for(int x = 0; x < lines.Length; x++)
{
if(x % 2 == 1 && newLines.Contains(lines[x])) //is odd and already exists
x++; \\skip next even line
else
newLines.Add(lines[x]);
}

逐行读写 - 代码:

//Delete file if exists
if(System.IO.File.Exists(@"/path/to/new_file.txt"))
System.IO.File.Delete(@"/path/to/new_file.txt")

List<string> newLines = new List<string>();
using (System.IO.StreamReader file = new System.IO.StreamReader(@"/path/to/file.txt"))
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(@"/path/to/new_file.txt", true))
{
string line = null;
int x = 0;
while((line = file.ReadLine()) != null)
{
if(x % 2 == 1 && newLines.Contains(line)) //is odd and already exists
x++; \\skip next even line
else
{
newLines.Add(line);
writer.WriteLine(line);
}
x++;
}
}

结果应该是:

+EVEN: some text 1
+ODD: some text 2
+EVEN: some text 3
-ODD: some text 2
-EVEN: some text 5
+ODD: some text 6
+EVEN: some text 2
+ODD: some text 7
+EVEN: some text 2
+ODD: some text 9

关于c# - 如何删除文本文件中具有奇数索引行和下一个偶数字符串的重复字符串并避免出现偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40624838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com