简体   繁体   中英

How can I create a C# string verbatim without carriage return

I have a strange situation. When I do a string verbatim like this:

string str = @"Hello 
World"

The string is created with a "\r\n" so that it's "Hello \r\nWorld". I want it to be created with just the new line, no carriage return so that it's "\n" only.

Now, I realize I can do:

str = str.Replace("\r", "")

But the string is a const variable specifically because I don't want a whole lot of instantiations and manipulations for performance (no matter how small), etc

Anyone know how I could do this so that, I could write a many line text stored as a const string with no "\r" that still appears formatted and easy to read in code?

It's your editor doing this to you, not C#.

If you take a look at your code in a hex editor, you'll see that the line "string str = @"Hello " ends with \r\n, not with just \n.

On Windows, by default, return is two characters \r\n, not just one like it is on Mac \n.

Most editors have an option to change this. However, eventually something's going to switch the file back to using \r\n on you when you're not looking.

The language doesn't provide a clean way around this. Just use a non-verbatim string or do a replace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM