I'm trying to calculate the byte size of a String
in Swift but I don't know the size of a single character; what is the byte size of a character?
Let's say I have a string:
let str = "hello, world"
I want to send that to some web service endpoint, but that endpoint only accepts strings whose size is under 32 bytes. How would I control the byte size of my string?
So a string size is 18 + (2 * number of characters) bytes. (In reality, another 2 bytes is sometimes used for packing to ensure 32-bit alignment, but I'll ignore that). 2 bytes is needed for each character, since . NET strings are UTF-16.
Swift – String Length/Count To get the length of a String in Swift, use count property of the string. count property is an integer value representing the number of characters in this string.
All of them are 2 bytes wide (on AVR platform), so if you don't have anything in it, it might actually be just 6 bytes total.
An empty String takes 40 bytes—enough memory to fit 20 Java characters.
It all depends on the character encoding, let's suppose UTF8:
let string = "abde"
let size = string.utf8.count
Note that not all characters have the same byte size in UTF8. If your string is ASCII, you can assume 1 byte per character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With