【问题标题】:Insert text in a text file at specific position在文本文件中的特定位置插入文本
【发布时间】:2013-10-18 01:15:12
【问题描述】:

我有一个文本文件,例如3 行:

Example Text
Some text here
Text

我想在“这里”之后直接添加一些文字,所以它看起来像这样:

Example Text
Some text hereADDED TEXT
Text

到目前为止,我的代码看起来是这样的,我使用了来自here 的一些代码,但它似乎不起作用。

List<string> txtLines = new List<string>();

string FilePath = @"C:\test.txt";

foreach (string s in File.ReadAllLines(FilePath))
{
    txtLines.Add(s);
}

txtLines.Insert(txtLines.IndexOf("here"), "ADDED TEXT");

using (File.Create(FilePath) { }

foreach (string str in txtLines)
{
    File.AppendAllText(FilePath, str + Environment.NewLine);
}

我的问题是: txtLines.IndexOf("here") 返回-1,从而抛出System.ArgumentOutOfRangeException

谁能告诉我我做错了什么?

【问题讨论】:

  • 问题是,IndexOf 检查列表中的条目,而不是该条目中的字符串。这表示您必须检查此列表中的每个 ntry(通过任何类型的循环)并检查您搜索的单词是否在此条目中。这意味着您需要先找到该条目,然后才能找到该条目中的位置
  • 您想只替换文本here 的第一个实例吗?如果不是,是否必须仅在第 2 行时才更换?如果有像there 这样的词呢?应该用whereADDED TEXT 代替吗?
  • 如果我想替换它的最后一个实例,那么我必须使用LastIndexOf吗?

标签: c# string text-files


【解决方案1】:

这是一段可以帮助您的代码。只需替换您的行 txtLines.Insert(txtLines.IndexOf("here"), "ADDED TEXT");与下面。它在这里找到第一个并将其替换为 hereADDED TEXT:

int indx=txtLines.FindIndex(str => str.Contains("here"));
txtLines[indx]= txtLines[indx].Replace("here", "hereADDED TEXT");

【讨论】:

    【解决方案2】:
                string filePath = "test.txt";
                string[] lines = File.ReadAllLines(FilePath);
                for (int i = 0; i < lines.Length; i++)
                {
                    lines[i] = lines[i].Replace("here", "here ADDED TEXT");
                }
    
                File.WriteAllLines(filePath, lines);
    

    它会做你想要的。

    【讨论】:

    • @Banshee 您可以编辑答案以改进它,而不仅仅是添加评论。 :)
    【解决方案3】:

    您是否有理由将所有文本加载到列表中?您可以在从文件中读取值时更新它们。

            string FilePath = @"C:\test.txt";
    
            var text = new StringBuilder();
    
            foreach (string s in File.ReadAllLines(FilePath))
            {
                text.AppendLine(s.Replace("here", "here ADDED TEXT"));
            }
    
            using (var file = new StreamWriter(File.Create(FilePath)))
            {
                file.Write(text.ToString());
            }
    

    【讨论】:

    • 如果我们想添加更多行而不重复之前的行两次怎么办,我看到这可行,但发生的事情是我试图先替换所有行,然后将其附加到最后我们怎么能完成这个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2010-11-22
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多