简体   繁体   English

为什么string.Replace无法正常工作?

[英]Why isn't string.Replace working as I expected?

I am writing c# code to replace certain words from a file. 我正在编写C#代码来替换文件中的某些单词。 The 2 line demo simple code that I have written is not working. 我编写的2行演示简单代码无法正常工作。 There is no error and Console.WriteLine is also giving correct output. 没有错误, Console.WriteLine也提供正确的输出。

string strFileContent = File.ReadAllText(@"C:\Users\toshal\Documents\TCS\stop_words.txt");
Console.WriteLine("strfilecontent" + strFileContent);
strFileContent = strFileContent.Replace("actually" , " ");

The string "actually" is not getting replaced in the file. 字符串“ actually”没有在文件中替换。 What can be the problem here? 这可能是什么问题?

Ofcourse it's not getting replaced in the file, as you only read the data and then alter it. 当然,它不会在文件中被替换,因为您只读取数据然后进行更改。

You`ll have to write it back to the file if want to apply the changes. 如果要应用更改,则必须将其写回到文件中。

string strFileContent = File.ReadAllText(@"C:\Users\toshal\Documents\TCS\stop_words.txt");
Console.WriteLine("strfilecontent" + strFileContent);
strFileContent = strFileContent.Replace("actually" , " ");

StreamWriter SW = File.CreateText(@"C:\Users\toshal\Documents\TCS\stop_words.txt");
SW.Write(strFileContent);
SW.Close();

You are creating a string with the replaced value, but you are never writing that value back to the file. 您正在使用替换后的值创建一个字符串,但是您从未将该值写回到文件中。 Therefore, the file remains unchanged. 因此,该文件保持不变。

To fix, add the following line to write the changed value back to the file: 要解决此问题,请添加以下行以将更改后的值写回到文件中:

string path = @"C:\Users\toshal\Documents\TCS\stop_words.txt";
string strFileContent = File.ReadAllText(path);
Console.WriteLine("strfilecontent" + strFileContent);
strFileContent = strFileContent.Replace("actually" , " ");
File.WriteAllText(path, strFileContent);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM