2

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), "##");

}
1
  • 4
    Note that there's no point in explicitly calling writer.Dispose() at the end of a using statement which will dispose it already. Commented Dec 2, 2010 at 9:28

5 Answers 5

12

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.

Sign up to request clarification or add additional context in comments.

Comments

7
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.

Comments

2

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

Comments

1

Refer to this MSDN Documentation

Just as others said, you need to use the return value from the replace operation.

Comments

0

Indeed, you solve it by getting the value of "Replace".

I was doing the following:

string code = "A123BCD";
code.Replace("123", "R");

and expected to have "ARBCD", but it gave me the initial result.

But it was necessary to do:

code = code.Replace("123", "R");

and all good.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.