John\\\'s" />
开发者

string.Replace does not work for quote

开发者 https://www.devze.com 2023-01-03 02:11 出处:网络
((string)dt.Rows[i][1]).Replace(\"\'\", \"\\\\\'\") 开发者_高级运维 I want the result that if any string have quote it change it into slash quote, e.g. John\'s -> John\\\'s
((string)dt.Rows[i][1]).Replace("'", "\\'")
开发者_高级运维

I want the result that if any string have quote it change it into slash quote, e.g. John's -> John\'s

but the above replace function is not working fine. it results like John\\'s

but if we change the code to

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

it gives the Result like John's

does change it anyway.


Because the backslash is the escape character, you need to tell it you want to treat it like a literal string. You do this by prepending an @ to the string:

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


Try a double backslash.

\\

Just one backslash is an escape; two is an actual backslash.


Use "\\'" or @"\'" for the replacement string. The backslash is the escape character in C# string literals. See the explanation of string literals in C#: \' in a string literal results in just a single quote. The reason this escape sequence exists, is because single quotes would require escaping if you were using a char literal ('\'').

The @ indicates that you're using verbatim string syntax, which allows for multi-line strings and eliminates the need to escape characters, apart from double quote, which you would escape with double double quotes (Visual Basic style).


Can you clarify please? Are you saying that

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

does not replace a ' with \' ?

Because I just tried it and it works fine. I.e. this

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

            Console.WriteLine(two);

Prints blah\'


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


You could 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\'s

John Steve\'s


If you want to prepare an SQL query, I think the best method is to replace a single ' for ''. For instance, if you wanto to search John O'Connor, this would work (at least in SQL Server, Access, Oracle, ...).

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

0

精彩评论

暂无评论...
验证码 换一张
取 消