0

I have a string containing new line code like this:

string line= "This is a line\nThis is another";

I would like to be able to translate "\n" to Environment.NewLine. "\n" is just one example, I would like to translate all or most special characters like tab "\t" for example as well.

I looked at this post: Can I convert a C# string value to an escaped string literal

However, the goal is not to write to console but to replace a string to a special character constant (like Environment.NewLine).

How can I do this the best way?

serializer
  • 1,003
  • 2
  • 13
  • 27
  • Environment.Newline returns a string which is appropriate for the current operating environment. It's not strictly a constant. But yes you could run a simple replace() function in your string and replace those characters with whatever Environment.Newline returns at the time you execute it. You can check the docs to see what it returns in each environment. https://learn.microsoft.com/en-us/dotnet/api/system.environment.newline?view=netframework-4.8 – ADyson Oct 24 '19 at 11:50
  • There is nothing like `Environment.NewLine` for tab characters (unless you invent your own). And `Environment.NewLine` isn't equivalent to `\n` unless you're running on Unix, so do you *really* want to convert all your existing `\n` characters to `Environment.NewLine`? (It would be the same as converting all the `\n` characters to `"\r\n"` character pairs if not running on Unix.) – Matthew Watson Oct 24 '19 at 11:55
  • 2
    `string newline = Regex.Replace(line, "\n|\r|\t", "SomethingElse")`, etc. maybe? – Jimi Oct 24 '19 at 12:32
  • find and replace – Stefan Oct 24 '19 at 14:34

0 Answers0