size of a string in bytes

rikki cattermole via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jan 28 06:56:03 PST 2017


On 29/01/2017 3:51 AM, Nestor wrote:
> Hi,
>
> One can get the length of a string easily, however since strings are
> UTF-8, sometimes characters take more than one byte. I would like to
> know then how many bytes does a string take, but this code didn't work
> as I expected:
>
> import std.stdio;
> void main() {
>   string mystring1;
>   string mystring2 = "A string of just 48 characters for testing size.";
>   writeln(mystring1.sizeof);
>   writeln( mystring2.sizeof);
> }
>
> In both cases the size is 8, so apparently sizeof is giving me just the
> default size of a string type and not the size of the variable in
> memory, which is what I want.
>
> Ideas?

A few misconceptions going on here.
A string element is not a grapheme it is a character which is one byte.

So what you want is mystring.length

Now sizeof is not telling you about the elements, its telling you how 
big the reference to it is. Specifically length + pointer. It would have 
been 16 if you compiled in 64bit mode for example.

If you want to know about graphemes and code points that is another story.
For that you'll want std.uni[0] and std.utf[1].

[0] http://dlang.org/phobos/std_uni.html
[1] http://dlang.org/phobos/std_utf.html


More information about the Digitalmars-d-learn mailing list