29

I am having a few problems with trying to replace backslashes in a date string on C# .net.

So far I am using:

string.Replace(@"\","-")

but it hasnt done the replacement. Could anyone please help?

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
intrigued_66
  • 16,082
  • 51
  • 118
  • 189

5 Answers5

58

string.Replace does not modify the string itself but returns a new string, which most likely you are throwing away. Do this instead:

myString= myString.Replace(@"\","-");

On a side note, this kind of operation is usually seen in code that manually mucks around with formatted date strings. Most of the time there is a better way to do what you want (which is?) than things like this.

Jon
  • 428,835
  • 81
  • 738
  • 806
5

as all of them saying you need to take value back in the variable.

so it should be

 val1= val1.Replace(@"\","-");

Or

 val1= val1.Replace("\\","-");

but not only .. below one will not work

 val1.Replace(@"\","-");
Dhaval
  • 2,801
  • 20
  • 39
2

Use it this way.

oldstring = oldstring.Replace(@"\","-");

Look for String.Replace return type.

Its a function which returns a corrected string. If it would have simply changed old string then it would had a void return type.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
2

You could also use:

myString = myString.Replace('\\', '-'));

but just letting you know, date slashes are usually forward ones /, and not backslashes \.

ericosg
  • 4,926
  • 4
  • 37
  • 59
1

As suggested by others that String.Replace doesn't update the original string object but it returns a new string instead.

myString= myString.Replace(@"\","-");

It's worthwhile for you to understand that string is immutable in C# basically to make it thread-safe. More details about strings and why they are immutable please see links here and here

Community
  • 1
  • 1
ABH
  • 3,391
  • 23
  • 26