Convert strings to/from C# syntax?

  • Thread starter Thread starter Michael A. Covington
  • Start date Start date
M

Michael A. Covington

Is there a built-in way to convert strings to and from their syntactic
representation in C#?

For example, suppose I have a string containing 'a' and a newline character
and 'b'. Is there some built-in way to render this as a string containing
the characters 'a' '\' 'n' 'b' ?

And the inverse?
 
Michael,

Do you mean you want a stirng literal like this:

"a\nb"

Or are you looking for a routine which will take the above literal and
give you the equivalent of:

"a\\nb"

Which when printed will give you "a\nb". If it is the latter, then
AFAIK, the answer is no, you would have to code this yourself.
 
Nicholas Paldino said:
Michael,

Do you mean you want a stirng literal like this:

"a\nb"

Or are you looking for a routine which will take the above literal and
give you the equivalent of:

"a\\nb"

Which when printed will give you "a\nb". If it is the latter, then
AFAIK, the answer is no, you would have to code this yourself.

The latter. Thanks.
 
Michael,
Do you mean you want a stirng literal like this:

"a\nb"

Or are you looking for a routine which will take the above literal
and give you the equivalent of:

"a\\nb"

Which when printed will give you "a\nb". If it is the latter,
then AFAIK, the answer is no, you would have to code this yourself.

Well, it is probably much easier to code it yourself, but you could use the
CodeDOM, e.g.

string myString = "a\nb";

CodePrimitiveExpression strExp = new CodePrimitiveExpression(mystring);
CSharpCodeProvider csharpcodeprovider = new CSharpCodeProvider();
StringWriter result = new StringWriter();
csharpcodeprovider.GenerateCodeFromExpression(strExp, result, new CodeGeneratorOptions());
return result.ToString();


Regards
Niels Harremoës
 
Back
Top