nikorio nikorio - 10 months ago 58
C# Question

How to remove specific content form strings on odd index lines in text file

I'm trying to replace for specific content in strings located only on the odd index number lines inside text document about 30 000 rows, and avoid it for even lines content. For example with index numbers just to see:

0. some text a2
1. a1 some text a3
2. some a3 text
3. some text a3
4. some a4 text

I want use list for string values which must be removed:

var valueList1 = new List<string> { "a1", "a2", "a3", "a4" };

But I'm not sure how to get line by index to replace it this way

if (index % 2 == 0)
string text = File.ReadAllText(path);
text = text.Replace("a1", "")
.Replace("a2", "")
.Replace("a3", "")
.Replace("a4", "");
File.WriteAllText(path, text);

to get this result in text document:

some text a2
some text
some a3 text
some text
some a4 text

Answer Source

This might do the trick for you

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;
        outputstring += string.Join(" ", line.Split().Where(w => !ignoreList.Contains(w)));

    outputstring += Environment.NewLine;
File.WriteAllText("some.txt", outputstring);

Reading the lines one by one and also used a variable (cnti) to count the lines we read. When the (cnti % 2 == 0) then we should leave the line as it is and in else part we should remove the strings from the array in ignoreList