26

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
  • 44,717
  • 22
  • 115
  • 201
mezamorphic
  • 14,525
  • 48
  • 112
  • 173

5 Answers5

53

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
  • 413,451
  • 75
  • 717
  • 787
4

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,763
  • 19
  • 38
1

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
  • 44,717
  • 22
  • 115
  • 201
1

You could also use:

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

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

ericosg
  • 4,757
  • 4
  • 32
  • 54
0

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,351
  • 22
  • 25