c# - 如何删除文本文件中奇数索引行上的特定内容形式字符串

标签 c# string replace

我正在尝试替换仅位于文本文档中大约 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/

相关文章:

c# - 反编译 .NET Replace 方法 (v4.6.1)

bash - 如何用行号替换文本文件中的整行

c# - 队列问题

c# - 长时间关闭应用程序时如何处理 'Not enough quota is available to process this command'异常

Python 日期时间对象

将字符串样式从 Arduino 转换为 C 通用样式

c# - 安全和短的服务器-客户端连接

c# - 可靠地重新连接到服务器 TCPClient C#

javascript - 如何使用正则表达式进行一些 Javascript 字符串操作?

javascript - 突出显示所有出现的字符串 - 不区分大小写