I have a string "I want to learn "c#"". How can I include the quotes before and after c#?
8 Answers
Escape them with backslashes.
"I want to learn \"C#\""
-
The reference manual is helpful: msdn.microsoft.com/en-us/library/ms228362.aspx– S.LottAug 11, 2010 at 12:17
-
2you cannot use multiple """ when formatting a string String.Format("<E><A KH=\"{0}\" ID=\"{1}\"/><C><T ID=\"{2}\" SID=\"{3}\"><L P=\"{4}\" N=\"{5}\" /></T></C></E>", params) will not work with multiple quotes. please use this answer that is marked correctly and get used to the habit of doing it.– New BeeSep 4, 2014 at 7:09
-
@ANeves fair to say that @newbee is wrong and that there's a Working counter-example:
string ok = string.Format(@"""{0}"" = {1}", "yes", true);
but don't link to stupid irrelevant pictures that waste peoples' time. This is a technical site– barlopAug 8, 2016 at 22:23
As well as escaping quotes with backslashes, also see SO question 2911073 which explains how you could alternatively use double-quoting in a @-prefixed string:
string msg = @"I want to learn ""c#""";
which results in:
I want to learn "c#"
-
I needed this in my replace logic. string nullHideDecimal = @"<HideDecimal i:nil=""true""/>"; and then dataContractXML = dataContractXML.Replace(nullHideDecimal, "<HideDecimal>0</HideDecimal>");– ZigglerJan 27, 2016 at 19:56
I use:
var value = "'Field1','Field2','Field3'".Replace("'", "\"");
as opposed to the equivalent
var value = "\"Field1\",\"Field2\",\"Field3\"";
Because the former has far less noise than the latter, making it easier to see typo's etc.
I use it a lot in unit tests.
Since .NET 7 you can use raw string literals, which allows to declare strings without escaping symbols:
string text = """
I want to learn "C#"
""";
Console.WriteLine(text); // Prints string 'I want to learn "C#"'
If string does not start or end with double quote you can even make it single line:
string text = """I want to learn "C#"!""";
Use escape characters for example this code:
var message = "I want to learn \"c#\"";
Console.WriteLine(message);
will output:
I want to learn "c#"
You can also declare a constant and use it each time. neat and avoids confusion:
const string myStrQuote = "\"";
The Code:
string myString = "Hello " + ((char)34) + " World." + ((char)34);
Output will be:
Hello "World."