我正在尝试打开.txt文件,搜索一个单词并将其替换为出现的任何位置。我可以这样做但不能使用.txt文件,只能使用我在.cs
文件中编写的字符串。这是我到目前为止的方法:
public void EditorialControl(string fileName, string word, string replacement)
{
List<string> list = new List<string>();
using (StreamReader reader = new StreamReader(directory + fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
list.Add(line);
}
reader.Close();
}
}
当我在Main()
中调用该方法时,应该使用参数word
并将其替换为我选择的替换字。
你能帮助我用代码替换方法中的单词吗?
答案 0 :(得分:6)
这比你想象的要简单:
File.WriteAllText(fileName, File.ReadAllText(fileName).Replace(word1, word2));
就是这样!
答案 1 :(得分:2)
您可以使用regex
string target=System.IO.File.ReadAllText(directory + fileName);
Regex.Replace(target,@"\b"+word+@"\b",replacement);