开发者

Tool to automatically covert a text string with special characters to a properly formatted c# string

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 spe开发者_开发知识库cial 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!


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.


The 99% solution is a one-liner:

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


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.)


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 + "\"";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜