The sizeof
method returns the number of code units in the string multiplied by the size (in bytes) of one code unit.
The code unit value of various types of strings are listed below:
ASCIIString
: 1 byte per character.UTF8String
: 1 byte per character.UTF16String
: 2 bytes per character.UTF32String
: 4 bytes per character.sizeof(str::AbstractString)
This method takes a string or a character as an argument.
This method returns an integer
value.
The code below demonstrates how we can use the sizeof
method:
## Get sizeof the string "Educative"println(sizeof("Educative"))## Get sizeof the string "z"println(sizeof("z"))## Get sizeof the character 'z'println(sizeof('z'))
Line 2: We use the sizeof
method to get the size of "Educative"
. We get 9
as the return value. The String values are stored as UTF-8
which takes only one byte. There are 9 UTF-8
characters in the string so 9
is returned as the result.
Line 5: We use the sizeof
method to get the size of "z"
. We get 1
as the return value.
Line 8: We use the sizeof
method to get the size of the character 'z'
. We get 4
as the return value because internally the character type (Char
) is stored as a 32-bit value so that any Unicode codepoint can fit in a Char
.