计算Swift字符串的大小(以字节为单位) [英] Calculate the size in bytes of a Swift String
问题描述
我正在尝试计算Swift中 String
的字节大小,但我不知道字符的大小是多少;一个编码的字节数是多少?
I'm trying to calculate the size in bytes of a String
in Swift but I don't know what the size of a character is; in how many bytes is one coded?
假设我有一个字符串:
let str =hello,world
Let's say I have a string:
let str = "hello, world"
我想将它发送到我的服务器,但我的服务器只接受32字节以下的字符串。我如何控制字符串的长度?
I want to send that to my server, but my server will only accept strings under 32 bytes. How would I control the length of my string?
推荐答案
这一切都取决于字符编码,让我们假设UTF8:
It all depends on the character encoding, let's suppose UTF8:
let string = "abde"
let size = string.utf8.count
请注意,并非所有字符在UTF8中都具有相同的字节大小。
如果你的字符串是ASCII,你可以假设每个字符有1个字节。
Note that not all characters have the same byte size in UTF8. If your string is ASCII, you can assume 1 byte per character.
这篇关于计算Swift字符串的大小(以字节为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!