String.Replace not working for quote

((string)dt.Rows[i][1]).Replace("'", "\\'") 

I want the result, if any line has a quote, change it to a slash, for example. John'sJohn\'s

but the above replacement function is not working fine. it looks like John\\'s

but if we change the code to

 ((string)dt.Rows[i][1]).Replace("'", "\'") 

he gives the result as John's

still change it.

+6
source share
7 answers

Since the backslash is an escape character, you need to say that you want to treat it as a literal string. You do this by adding @ to the line:

 ((string)dt.Rows[i][1]).Replace("'", @"\'") 
+16
source share

Try a double backslash.

\\

Only one backslash is escape; two is the backslash.

+9
source share

Use "\\'" or @"\'" for the replacement string. The backslash is an escape character in C # string literals. See Explanation of String Literals in C #: \' in a String Literal results in only one quote. The reason this escape sequence exists is because single quotes will require escaping if you use the char literal ( '\'' ).

@ indicates that you are using string string syntax that allows you to use multi-line strings and eliminates the need to avoid characters other than double quotes, which you could avoid with double double quotes (Visual Basic style).

+4
source share

Can you please clarify? You say that

 ((string)dt.Rows[i][1]).Replace("'", "\\'") 

doesn't replace a ' with \' ?

Because I just tried it and everything works fine. That is it

  string one = "blah'"; string two = one.Replace("'", "\\'"); Console.WriteLine(two); 

Print blah\'

+3
source share

Replace ("'", "\") use double slash

+1
source share

You can use something like this:

 private static string replace(String input) { return Regex.Replace(input, "('|\")", "\\'"); } static void Main(string[] args) { String value1 = "John Steve's"; String value2 = "John Steve\"s"; Console.WriteLine(replace(value1)); Console.WriteLine(replace(value2)); } 

Results:

John Steve [/ p>

John Steve [/ p>

0
source share

If you want to prepare a SQL query, I believe that the best method is to replace one with a “for”. For example, if you want to search for John O'Connor, this will work (at least in SQL Server, Access, Oracle, ...).

select ... from users where username = 'Jonh O''Connor'

0
source share

All Articles