How to deal with quotes within quotes in C#?
Main Question:
Is there a way to insert ONE double quotation in a string in C#Information:
I am trying to perform something like the following SQL Select statement in C#SELECT Name FROM Production.Product
WHERE CONTAINS(Name, '"chain*"');
I interpreted it this as follows:
string selectCommand= @"select Name from Production.Products
WHERE contains (Name,'\"" + chain+ "*\"')");
But I'm getting the string back as:
" WHERE contains (Name,'"chain"')"
I've also tried the way in this SOF question but it didn't work either!:
string selectCommand= @"select Name from Production.Products
where contains (doc.document_name,'"""""" + full + """"""开发者_高级运维')");
If you look at the documentation for string literals you will find that there are two formats. The regular format where you have to escape all teh following characters:
', ", \, 0, a, b, f, n, r, t, u, U, x, v.
So your string should be written as follows:
string query = "WHERE CONTAINS(Name, \'\"chain*\"\');";
or verbatim literals, which are preceded with an 'at' symbol, where you only escape double quotes by 'doubling up':
string query = @"WHERE CONTAINS(Name, '""chain*""');";
So just drop the '@' from your string and it will work.
Its because you have a @
at the start of your string
string selectCommand= "select Name from Production.Products where contains (doc.document_name,\'\"" + full + "*\"\');";
You basically need to escape the '
and "
Simply drop the @ at the beginning of your string and it should work.
The reason why the backslash is preserved in your string is because you've told the string not to replace escaped character sequences by placing the @ in front of the string. Removing the @ will allow your escaped characters to be, well, escaped.
Something like this maybe:
string full = "abc";
string selectCommand= @"select Name from Production.Products where contains (doc.document_name,'""" + full + "*\"')";
The "@" won't help you here. Remove it, and you should be fine. This should work:
Console.WriteLine("...(doc.document_name,'\"" + full + "*\"')");
If you really want to keep the "@", try this:
Console.WriteLine(@"...(doc.document_name,'""" + full + "*\"')");
精彩评论