Anshul
Anshul

Reputation: 21

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

}

Upvotes: 2

Views: 5502

Answers (5)

Yudner
Yudner

Reputation: 623

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.

Upvotes: 0

Prasanna K Rao
Prasanna K Rao

Reputation: 1086

Refer to this MSDN Documentation

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

Upvotes: 1

TalentTuner
TalentTuner

Reputation: 17556

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

Upvotes: 2

gpvos
gpvos

Reputation: 2802

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.

Upvotes: 7

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

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.

Upvotes: 12

Related Questions