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?
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?
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.
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(@"\","-");
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.
You could also use:
myString = myString.Replace('\\', '-'));
but just letting you know, date slashes are usually forward ones /
, and not backslashes \
.
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