How to concatenate double quotes with slashes to a string value?
Expected out put: "\"Hello World\""
Here is my code:
string term="Hello World";
string output = "\"" + term + "\"";
above code result is giving Hello World
How to concatenate double quotes with slashes to a string value?
Expected out put: "\"Hello World\""
Here is my code:
string term="Hello World";
string output = "\"" + term + "\"";
above code result is giving Hello World
To output quotes and slashes you should use slash before symbols(slash, quotes etc.) In your case
string term = "Hello World";
string output = "\\\"" + term + "\\\"";
First slash is used to output second slash and third slash used to output quotes. I don't know whether I should consider first and last quotes in your question or not. If you want to output them just add
\"
You must escape every char, that you want to display.
\"Hello World\"
:
string output = "\\\"" + term + "\\\"";
"\"Hello World\""
:
string output = "\"\\\"" + term + "\\\"\"";
Sure you could add the escape characters yourself, but what if you want to escape values inside the string too? You could write that loop yourself easily enough, or;
public string Escape(string value)
{
using (var writer = new StringWriter())
{
using (var provider = CodeDomProvider.CreateProvider("CSharp"))
{
provider.GenerateCodeFromExpression(new CodePrimitiveExpression(value), writer, null);
return writer.ToString();
}
}
}