Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing backslash in a string

Tags:

string

c#

.net

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?

like image 818
mezamorphic Avatar asked May 25 '12 10:05

mezamorphic


People also ask

How do you replace a backslash in a string in Java?

replaceAll("\\/", "/");

How do you handle a backslash in a string?

If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string: var s = "\\Tasks"; // or var s = @"\Tasks"; Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.

How do you replace a backslash in a string Python?

We can use the replace() function to replace the backslashes in a string with another character. To replace all backslashes in a string, we can use the replace() function as shown in the following Python code.

How do you replace a single slash in Java?

Replacing a Single Backslash( \ ) With a Double Backslash( \\ ) Using the replaceAll() Method. This is another solution that you can use to replace the backslashes. Here, we used the replaceAll() method that works fine and returns a new String object.


1 Answers

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.

like image 88
Jon Avatar answered Sep 21 '22 22:09

Jon