Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with quotes within quotes in C#?

Tags:

string

c#

quotes

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 + """"""')");
like image 893
Majd Avatar asked Feb 25 '11 06:02

Majd


People also ask

How do you quote a quote within a quote?

Quotations within a QuotationUse single quotation marks to enclose quotes within another quotation. The reporter told me, "When I interviewed the quarterback, he said they simply 'played a better game. '"

How do you escape quotation marks in C?

\" - escape sequence Since printf uses ""(double quotes) to identify starting and ending point of a message, we need to use \" escape sequence to print the double quotes.

Why do we use double quotes in C?

In C and C++ the single quote is used to identify the single character, and double quotes are used for string literals. A string literal “x” is a string, it is containing character 'x' and a null terminator '\0'. So “x” is two-character array in this case.

Can you have a string with a quote inside it?

Sometimes you might want to place quotation marks (" ") in a string of text. For example: She said, "You deserve a treat!" As an alternative, you can also use the Quote field as a constant.


2 Answers

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.

like image 168
ColinE Avatar answered Sep 19 '22 11:09

ColinE


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 "

like image 44
Jason Jong Avatar answered Sep 18 '22 11:09

Jason Jong