C # line - creating an unbound backslash

I am using .NET code (C #) to write to a database that interacts with a Perl application. When a single quote appears in a string, I need to "escape" from it. IOW, the name O'Bannon must be converted to O\'Bannon for the UPDATE database. However, all string manipulation efforts (like Replace) generate an escape character for the backslash, and I end up O\\'Bannon .

I know that it actually generates a second backslash, because I can read the resulting value of the database field (i.e. this is not just an IDE debug value for the string).

How can I get only one backslash in the output string?

R

+4
source share
4 answers

Well i did

 "O'Bannon".Replace("'","\\'") 

and result

 "O\'Bannon" 

Is this what you want?

+5
source

You can use "\\" , which is an escape char followed by a backslash.

See the Escape Sequences list here: http://msdn.microsoft.com/en-us/library/h21280bw.aspx

+2
source

it's even better to assign a var variable so you can check it if necessary

 var RepName = "O'Bannon"; var Repstr = RepName.Replace("'","\\'"); 
+1
source

You can also use the shorthand line

 s = s.Replace("'", @"\'"); 
+1
source

Source: https://habr.com/ru/post/1391694/


All Articles