如何将字符串转换为带有unix行尾的字节? [英] How do I convert a string to bytes with unix line endings?
问题描述
如果我使用以下方法将字符串转换为字节:
If I convert a string to bytes using:
byte[] ascii = new System.Text.ASCIIEncoding().GetBytes(myString);
然后,我取回的字节使用Windows行结尾.如何使用Unix行尾将其转换?
Then the bytes I get back use Windows line endings. How can I convert it using Unix line endings?
推荐答案
行尾与编码无关.如果要将Windows行尾转换为Unix行尾,请在字符串本身中执行以下操作:
The line endings are independent of the encoding. If you want to convert Windows line endings to Unix line endings, do that in the string itself:
myString = myString.Replace("\r\n", "\n");
我个人而言,我尽量避免使用ASCII-您是否绝对确定它永远不需要任何带重音的字符?如果可以选择的话,我通常会使用UTF-8:
Personally I avoid using ASCII wherever possible, by the way - are you absolutely sure it will never need any accented characters? If I get the choice, I usually use UTF-8:
myString = myString.Replace("\r\n", "\n");
byte[] bytes = Encoding.UTF8.GetBytes(myString);
如果要在某处写入流,则可以选择使用StreamWriter
或File.CreateText
等.然后只需指定一次编码,而无需自己处理原始字节.
If you're writing to a stream somewhere, any alternative is to use StreamWriter
, or File.CreateText
etc. Then you specify the encoding once but don't need to deal with the raw bytes yourself.
这篇关于如何将字符串转换为带有unix行尾的字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!