0

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

sridharnetha
  • 2,104
  • 8
  • 35
  • 69
  • @RandRandom please note expecting output `"\"Hello World\""` not just `"Hello World"` – sridharnetha Jun 22 '22 at 11:25
  • `above code result is giving Hello World` seems a wrong statement as it outputs `"Hello World"` – Rand Random Jun 22 '22 at 11:25
  • `string output = $"\"{term}\"";` – Dmitry Bychenko Jun 22 '22 at 11:32
  • 1
    The number of people not reading this question properly is worrying. OP wants the text output to include the quotes and slashes. – DavidG Jun 22 '22 at 11:35
  • 1
    Does this answer your question? [How do I write a backslash (\‌) in a string?](https://stackoverflow.com/questions/18532691/how-do-i-write-a-backslash-in-a-string) – Charlieface Jun 22 '22 at 11:37
  • Btw if your code should be more dynamic you could consider implementing one of those solutions https://stackoverflow.com/questions/323640/can-i-convert-a-c-sharp-string-value-to-an-escaped-string-literal | see an example here: https://dotnetfiddle.net/iV7k6M – Rand Random Jun 22 '22 at 11:39

5 Answers5

1

Does this help?

string output = "\"\\\"" + term + "\\\"\"";

Live Demo

novice in DotNet
  • 771
  • 1
  • 9
  • 21
1
string output = "\"\\\"" + term + "\\\"\"";
YungDeiza
  • 3,128
  • 1
  • 7
  • 32
1

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

\" 
NoName
  • 181
  • 8
0

You must escape every char, that you want to display.

\"Hello World\":

string output = "\\\"" + term + "\\\""; 

"\"Hello World\"":

string output = "\"\\\"" + term + "\\\"\"";
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Spoomer
  • 38
  • 5
0

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();
        }
    }
}
Jeremy Lakeman
  • 9,515
  • 25
  • 29