I'm wondering if I can know how long in bytes for a string
in C#, anyone know?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding
class.
or try this
System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
System.Text.ASCIIEncoding.ASCII.GetByteCount(string);
回答2:
From MSDN:
A
String
object is a sequential collection ofSystem.Char
objects that represent a string.
So you can use this:
var howManyBytes = yourString.Length * sizeof(Char);
回答3:
System.Text.ASCIIEncoding.Unicode.GetByteCount(yourString);
Or
System.Text.ASCIIEncoding.ASCII.GetByteCount(yourString);