C Style String Encoding
Today I was creating a couple of parsers that needed to pick up some default text for templating. Basically it’s some XML text that serves as a header to the XML document. Rather than writing it out using the XmlWriter I just want to grab the header (header, schema etc. which won’t change) and then only write the body as Xml. This certainly is easier than creating the schema with XmlWriter…
So I run into this all of the time how do you quickly create a C compatible string from the text? C# has the nice @"string" syntax that makes it fairly easy to create long block strings but it still requires encoding quotes. So since I’ve done this a million times I wrote a quick utlity that does this for me. I paste the string into the form and it returns me a C# formatted string:

You paste a string in the top and it dumps the formatted string expression into the window below and your clipboard.
Obviously this is a super trivial thing to do but it’s a useful utility to have around. I can’t recount the number of times I take a string from somewhere and manual encode the damn quotes <s>. Well, no more. I remember having seen an add-in for .NET some time related to this but I couldn’t find it and frankly I rather not add anything like this into the VS environment anyway.
Anyway, maybe some of you find this useful. You can grab the CStringEncoder file from here.
Other Posts you might also like
The Voices of Reason
# re: C Style String Encoding
I suppose the true CString encoding will come handy in C++ though <s>. It'll return a string like this:
"<head runat=\"server\">\r\n" + " <title>Web Form Localization</title>\r\n" + " <link href=\"../Westwind.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n" + "</head>"
Ok, I'm stretching for it now...
# re: C Style String Encoding
# re: C Style String Encoding
# re: C Style String Encoding
I really wonder about that choice though: The @"" syntax is a lot cleaner ESPECIALLY if you create multiline strings since there's only one escaped character (") vs. 10 or so. The @ syntax certainly is nice for complex SQL statements because you can pretty much just paste a SQL statement into text.
I guess I'm spoiled from my FoxPro background where there is:
TEXT TO VarName <text expression with any content> ENDTEXT
and 3 different string delimiters, both of which made it much easier to create complex strings especially for things like JavaScript or JavaScript expressions which is one thing I was just struggling with - the single C# string delimiter really gets in the way when you need to create content that includes other strings using double or single quotes alot. Or heck ASP.NET page level <% %> expressions - that's where extra delimiters would REALLY help.
# re: C Style String Encoding
# re: C Style String Encoding
Got a working one :)
# re: C Style String Encoding