How to include quotes in a string

C#StringDouble Quotes

C# Problem Overview


I have a string "I want to learn "c#"". How can I include the quotes before and after c#?

C# Solutions


Solution 1 - C#

Escape them with backslashes.

"I want to learn \"C#\""

Solution 2 - C#

As well as escaping quotes with backslashes, also see SO question [2911073][1] which explains how you could alternatively use double-quoting in a @-prefixed string:

string msg = @"I want to learn ""c#""";

[1]: https://stackoverflow.com/questions/2911073/how-can-i-put-quotes-in-a-string "2911073"

Solution 3 - C#

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.

Solution 4 - C#

string str = @"""Hi, "" I am programmer";

OUTPUT - "Hi, " I am programmer

Solution 5 - 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#"

Solution 6 - C#

You can also declare a constant and use it each time. neat and avoids confusion:

const string myStrQuote = "\"";

Solution 7 - C#

The Code:

string myString = "Hello " + ((char)34) + " World." + ((char)34);

Output will be:

> Hello "World."

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlearningView Question on Stackoverflow
Solution 1 - C#kennytmView Answer on Stackoverflow
Solution 2 - C#NeilDurantView Answer on Stackoverflow
Solution 3 - C#James CochraneView Answer on Stackoverflow
Solution 4 - C#someshView Answer on Stackoverflow
Solution 5 - C#Łukasz W.View Answer on Stackoverflow
Solution 6 - C#ChagbertView Answer on Stackoverflow
Solution 7 - C#Ariel TerraniView Answer on Stackoverflow