开发者

How to include quotes in a string

开发者 https://www.devze.com 2023-01-11 16:15 出处:网络
I have a st开发者_StackOverflow中文版ring \"I want to learn \"c#\"\".How can I include the quotes before and after c#?Escape them with backslashes.

I have a st开发者_StackOverflow中文版ring "I want to learn "c#"". How can I include the quotes before and after c#?


Escape them with backslashes.

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


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#""";


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.


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

OUTPUT - "Hi, " I am programmer


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 = "\"";


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#"!""";


The Code:

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

Output will be:

Hello "World."

0

精彩评论

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