tags:

views:

112

answers:

4

Hi... I had this really useful app in VB6 & I was wondering if anyone knows of an equivalent one for c#...

Basically the vb6 app allowed you to paste text into an input box and then it would produce an output text that was correctly formatted (with special characters) so that you could paste it directly in your code without having to convert special characters.

For example...

Input

Say "Hello"

Output

string s = "Say \"Hello\"";

If anyone know of an equivalent free tool for c#, or something I can do in VS2008 that would avoid me having to do this process manually, it would be appreciated!

+2  A: 

The 99% solution is a one-liner:

return "\"" + textBox1.Text.Replace("\", "\\").Replace("\"", "\"") + "\"";

Hans Passant
Thanks nobugz... but when I try and paste this code into a c# project I get an errore.g. public string Convert(string input){ return "\"" + input.Replace("\", "\\").Replace("\"", "\"") + "\"";}
Mark Pearl
Please don't make me guess at the error. Make it static.
Hans Passant
+2  A: 

The C# language specification says that the only special character in a verbatim string literal (@"...") is the double quote ("), which can be escaped by duplicating it (""). So, the algorithm you want is quite simple (untested, beware of typos):

outputTextBox.Text = "string s = @\"" + inputTextBox.Text.Replace("\"", "\"\"") + "\";";

Example:

a       => string s = @"a";
a "b" c => string s = @"a ""b"" c";
a\b c   => string s = @"a\b c";

Since verbatim string literals support linebreaks, this should even work for multi-line text.

(Actually, since the only character you need to escape is the double quote, I'm wondering whether it's even worth writing this program.)

Heinzi
Thanks for the suggestion...
Mark Pearl
+2  A: 

Have a look at the Smart Paster add-in.
It allows you to paste the text in the clipboard in various formats, and does this kind of escaping for you.

Paolo Tedesco
Thank you, that was exactly what I was looking for orsogufo! That is going to be a real timesaver...
Mark Pearl
Glad it helped :)
Paolo Tedesco
+1  A: 

nobugz's solution works fine for a single line of text, but you'd need to change it to be able to cope with multiple lines:

text = text.Replace("\r", @"\r").Replace("\n", @"\n");
text = text.Replace("\\", "\\\\").Replace("\"", "\\\"");
return "\"" + text + "\"";

Or if you want a verbatim literal then you need only escape quotes:

text = text.Replace("\"", "\"\"")
return "@\"" + text + "\"";
Will Vousden
Thanks for the feedback.. its much appreciated
Mark Pearl