0
string str1="xxx";
string str2=@"sss" + str1 + "ddd";
Console.WriteLine(str2);

The above code gives:

sssxxxddd

But what I want is:

sss" + str1 + "ddd

How to do that?

Sam Axe
  • 33,313
  • 9
  • 55
  • 89

5 Answers5

4

You can escape the quotes by preceding them with a backslash (\).

string str1 = "xxx";
string str2 = "sss\" + str1 + \"ddd";
Console.WriteLine(str2);

For strings prefixed with the @ character, quotes are escaped by placing two together (i.e., string str2 = "sss"" + str1 + ""ddd").

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • Thanks! the placing two quotes to escape when using @ is exactly what I want to know! –  Jan 11 '18 at 04:30
3

Here you go:

 Console.WriteLine("sss\" + str1 + \"ddd");
Gordon
  • 516
  • 1
  • 3
  • 13
  • This does not answer the question. – Enigmativity Jan 11 '18 at 02:01
  • @Enigmativity I changed the answer, but I think he/she can figure it out with my original answer. I tend not to give direct "copy and paste" answer to questions. – Gordon Jan 11 '18 at 02:07
  • Yes this works, but I'm more interested in knowing how to do it WITHOUT removing @. My question was not clear enough. Thank you anyway. –  Jan 11 '18 at 04:32
3
        string str1 = "xxx";
        string str2 = @"sss"" + str1 + ""ddd";
        Console.WriteLine(str2);

        string str3 = "xxx";
        string str4 = "sss\" + str1 + \"ddd";
        Console.WriteLine(str4);
        Console.ReadKey();
Xss
  • 211
  • 1
  • 12
-2
string str1="xxx";
string str2=@"sss""" + str1 + @"""ddd";
Console.WriteLine(str2);

or

string str1="xxx";
string str2="sss\"" + str1 + "\"ddd";
Console.WriteLine(str2);

This will give you an answer like: sss"xxx"ddd. If you want an answer like sss" + str1 + "ddd then you replace the second line with this: string str2=@"sss"" + str1 + ""ddd";

-3

You may try this

string str1="xxx";
string str2=@"sss\"" + str1 + "\"ddd";
Console.WriteLine(str2);

EDITED

string str1 = "\"xxx\""; string str2 = "sss" + str1 + "ddd"; Console.WriteLine(str2); Console.ReadLine();

OreaSedap
  • 21
  • 7