Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the size in bytes of a Swift String

Tags:

string

ios

swift

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?

like image 952
Randy Avatar asked Sep 05 '16 18:09

Randy


People also ask

How do you calculate string size in bytes?

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.

How do I find the length of a string in Swift?

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.

What is the size of a string variable in bytes?

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.

How much space does a string need?

An empty String takes 40 bytes—enough memory to fit 20 Java characters.


1 Answers

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.

like image 121
Sulthan Avatar answered Sep 25 '22 09:09

Sulthan