How to cut off string based on its byte volume

Hi expert,

Does anybody know how to cut a string based on its byte volume?
I need to cut off a string that may contain both 1 byte char and 2 byte char based on its byte volume lower or equal to 40 byte. (So final product of string is 39 or 40 byte.)

I found string.length option but it only returns a number of char not byte…

Thanks in advance,

Note: I found a way but it might be low performance.

  1. Do while byte count > 40
  2. Get string byte count by below method.