How to know the size of the string in bytes?

后端 未结 3 1479
梦毁少年i
梦毁少年i 2020-11-27 14:50

I\'m wondering if I can know how long in bytes for a string in C#, anyone know?

相关标签:
3条回答
  • 2020-11-27 15:14
    System.Text.ASCIIEncoding.Unicode.GetByteCount(yourString);
    

    Or

    System.Text.ASCIIEncoding.ASCII.GetByteCount(yourString);
    
    0 讨论(0)
  • 2020-11-27 15:15

    From MSDN:

    A String object is a sequential collection of System.Char objects that represent a string.

    So you can use this:

    var howManyBytes = yourString.Length * sizeof(Char);
    
    0 讨论(0)
  • 2020-11-27 15:27

    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);
    
    0 讨论(0)
提交回复
热议问题