我试图替换仅位于文本文档中大约30 000行的奇数索引号行上的字符串中的特定内容,并避免使用偶数行内容。例如,索引号只是为了看:
0. some text a2
1. a1 some text a3
2. some a3 text
3. some text a3
4. some a4 text
我想使用list来表示必须删除的字符串值:
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
答案 0 :(得分:1)
这可能会为你做到这一点
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