I create the following for truncating a string in java to a new string with a given number of bytes.
String truncatedValue = \"\";
String curren
Binary search approach in scala:
private def bytes(s: String) = s.getBytes("UTF-8")
def truncateToByteLength(string: String, length: Int): String =
if (length <= 0 || string.isEmpty) ""
else {
@tailrec
def loop(badLen: Int, goodLen: Int, good: String): String = {
assert(badLen > goodLen, s"""badLen is $badLen but goodLen is $goodLen ("$good")""")
if (badLen == goodLen + 1) good
else {
val mid = goodLen + (badLen - goodLen) / 2
val midStr = string.take(mid)
if (bytes(midStr).length > length)
loop(mid, goodLen, good)
else
loop(badLen, mid, midStr)
}
}
loop(string.length * 2, 0, "")
}