-2

I have a string like this:

-Backcheck = 0 Days 2 Hours 15 Minutes\n-Backcheck = 0 Days 1 Hours 13 Minutes

before display it I want to change \n for \n Median and remove -Backcheck for nothig so I do:

tt.BackcheckToCorrectionsString.Replace("\n", "\n Median ");
tt.BackcheckToCorrectionsString.Replace("-Backcheck", "");
   //Display
  e.Text = $"Mean {tt.BackcheckToCorrectionsString}";

But it just return same value, what am I doing wrong? Regards

Pepe
  • 57
  • 4
  • 2
    `Replace` does not alter the string you pass in. It returns the result as a new string. – Blorgbeard Sep 06 '18 at 23:37
  • If you are doing many replaces in a single string, consider using StringBuilder.Replace. It does the replaces in place (unlike string.Replace) and does it more efficiently. The StringBuilder is not immutable. – Flydog57 Sep 07 '18 at 00:32

1 Answers1

-1

The .Replace() function returns a new string. It does not modify the current string in place, because strings in .Net are immutable. You need this:

tt.BackcheckToCorrectionsString = tt.BackcheckToCorrectionsString.
          Replace("\n", "\n Median ").
          Replace("-Backcheck", "");
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • You can chain the replace statement: `tt.BackcheckToCorrectionsString = tt.BackcheckToCorrectionsString.Replace("\n", "\n Median ").Replace("-Backcheck", "");` – J3soon Sep 06 '18 at 23:39
  • 1
    @J3soon incorporated that into the answer and improved formatting. – Joel Coehoorn Sep 06 '18 at 23:43
  • 1
    why do you answer an obviously duplicate question? desperate for reputation? – Selman Genç Sep 06 '18 at 23:49
  • For users with <100 rep, they tend to get upset when their questions are closed as a dupe. I feel this is part of what has made Stack Overflow feel unwelcoming to so many, so if I can answer quickly, I do. – Joel Coehoorn Sep 06 '18 at 23:50