Calc utf-8 string size in bytes?

2020-03-08 08:11发布

问题:

I have a string of utf8.

I need to get its size. ( bytes)

Does it always x2 ? // I mean multiply by 2

is there any .net function for this ?

p.s.

im asking this question becuase of my latest question ...I need ( in mempry mapped file) to calc the offset of a string ( utf8 ) - from another process..

回答1:

No, it is not always x2 for UTF-8 and changes based on the actual contents. For ASCII characters it is 1 byte, but can go into several bytes for large code-point values. You want:

string s = // your string
int len = Encoding.UTF8.GetByteCount(s);