String.Replace not replacing the string during runtime
The following line in the below code 开发者_运维技巧doesn't cause any effect:
string1.Replace(string1.Substring(firstchar, lastchar - firstchar), "##");
string1
remains unchanged and I get the same index returned when using IndexOf.
while (firstchar != string1.LastIndexOf("test"))
{
firstchar = string1.IndexOf("test");
lastchar = string1.IndexOf(" ");
using (StreamWriter writer = new StreamWriter("C:\\textfile1.txt"))
{
writer.WriteLine(string1.Substring(firstchar, lastchar - firstchar));
writer.WriteLine();
writer.Dispose();
}
string1.Replace(string1.Substring(firstchar, lastchar - firstchar), "##");
}
Change
string1.Replace(string1.Substring(firstchar, lastchar - firstchar), "##");
to
string1 = string1.Replace(string1.Substring(firstchar, lastchar - firstchar), "##");
string.Replace
does not alter the original string, but returns the altered string as it's return value.
string1 = string1.Replace(...);
From the docs:
String.Replace
returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
Strings are immutatble so if you change in a string object , a new object is created so you need to have the reference of the newly created string.
so
string1 = string1.Replace(string1.Substring(firstchar, lastchar - firstchar), "##");
will solve the issue
Refer to this MSDN Documentation
Just as others said, you need to use the return value from the replace
operation.
精彩评论