我正在尝试替换仅位于文本文档中大约 30 000 行的奇数索引号行上的字符串中的特定内容,并避免替换偶数行内容。例如,索引号只是为了查看:
0. some text a2
1. a1 some text a3
2. some a3 text
3. some text a3
4. some a4 text
我想对必须删除的字符串值使用列表:
var valueList1 = new List<string> { "a1", "a2", "a3", "a4" };
但我不确定如何通过索引获取行以这种方式替换它
if (index % 2 == 0)
{
string text = File.ReadAllText(path);
text = text.Replace("a1", "")
.Replace("a2", "")
.Replace("a3", "")
.Replace("a4", "");
File.WriteAllText(path, text);
}
在文本文档中得到这个结果:
some text a2
some text
some a3 text
some text
some a4 text
最佳答案
这可能对你有用
int cnti = 0;
var ignoreList = new List<string> { "a1", "a2", "a3", "a4" };
string outputstring = string.Empty;
foreach(string line in File.ReadLines("some.txt"))
{
if(cnti % 2 == 0)
outputstring += line;
else
outputstring += string.Join(" ", line.Split().Where(w => !ignoreList.Contains(w)));
outputstring += Environment.NewLine;
cnti++;
}
File.WriteAllText("some.txt", outputstring);
逐行读取,还使用了一个变量(cnti)来统计我们读取的行数。当 (cnti % 2 == 0)
时,我们应该保留该行,在其他部分,我们应该从 ignoreList
关于c# - 如何删除文本文件中奇数索引行上的特定内容形式字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40623528/