Counting the number of bytes used by characters of a String

  • Thread starter Thread starter Nicolas
  • Start date Start date
N

Nicolas

Hi,

How one can count the number of bytes used by all the characters of a
String ?

i.e. String.Length * 2 (a char is 2 bytes long), but using more "proper"
ways.

Thanks.
 
Nicolas said:
How one can count the number of bytes used by all the characters of a
String ?

In what encoding? In the CLR itself, or in a particular encoding?
 
Rajagopal Pasupuleti said:
you can use GetByteCount method of String Class

I think you mean the GetByteCount method of the Encoding class - there
is no such method in the String class.
 
Jon said:
In what encoding? In the CLR itself, or in a particular encoding?

Just as it is, I mean the space it takes on RAM.
I think a String class stores a string as an array of char, just want to
know what place this array occupies.
 
Nicolas said:
Just as it is, I mean the space it takes on RAM.
I think a String class stores a string as an array of char, just want to
know what place this array occupies.

To be very clear:

String str = "hi";

How can I find the size of str in mem ? (no matter if we do not consider
the size of the enclosing class itself)
 
Nicolas said:
Just as it is, I mean the space it takes on RAM.
I think a String class stores a string as an array of char, just want to
know what place this array occupies.

It's not actually an array of char itself - string is a very unusual
type, in that the size of the object itself depends on the contents.

I believe the size of the object is 20+(n/2)*4 where n is the number of
characters in the string. (The result of n/2 is rounded down.)
 
Back
Top