问题
I want to print two double quotes in C# as the output. How to do this?
I mean the output should be: "" Hello World ""
回答1:
Console.WriteLine("\"\" Hello world \"\"");
or
Console.WriteLine(@""""" Hello world """"");
回答2:
If you want to put double quotes in a string you need to escape them with a \
eg:
string foo = "here is a \"quote\" character";
If you want to literally output "" Hello World ""
then you'd need:
string helloWorld = "\"\" Hello World \"\"";
output(helloWorld);
(where output is whatever method you are using for output)
回答3:
One way is to escape the quotes:
var greeting = "\"Hello World\"";
回答4:
When you want to use special character which are exist in you language add \ before that character then special character start behaving as a string. In your case use like this
\"Hello word\"
Out put
"Hello word"
回答5:
you can output with the @
, which will automatically escape special characters.
string output = "\"\" Hello World \"\"";
string output = @""""" Hello World """"";
回答6:
If you have to do this often and you would like this to be cleaner in code you might like to have an extension method for this.
This is really obvious code, but still I think it can be useful to grab and make you save time.
/// <summary>
/// Put a string between double quotes.
/// </summary>
/// <param name="value">Value to be put between double quotes ex: foo</param>
/// <returns>double quoted string ex: "foo"</returns>
public static string PutIntoQuotes(this string value)
{
return "\"" + value + "\"";
}
Then you may call foo.PutIntoQuotes() or "foo".PutIntoQuotes(), on every string you like.
Hope this help.
回答7:
Escape them:
Console.WriteLine("\"Hello world\"");
回答8:
Console.WriteLine("\"\"Hello world\"\"");
The backslash ('\') character precedes any 'special' character that would otherwise be interpreted as your code instead of as part of the string to be output. It's a way of telling the compiler to treat it as a character part of a string as opposed to a character that would otherwise have some sort of purpose in the C# language.
回答9:
Using a @-char before the 'normal' double quotes will result in printing every special char between those dubble quotes
string foo = @"foo "bar"";
回答10:
Use a backslash before the double quotes: \"
回答11:
StringBuilder sb = new StringBuilder();
sb.Append("\"Hello World \"");
string s = sb.ToString();
来源:https://stackoverflow.com/questions/9582781/c-sharp-two-double-quotes