Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import scala.annotation.tailrec
- object test extends App {
- def cutOff(s: String, maxBytes: Int): String = {
- @tailrec
- def loop(chars: Seq[Char], nchars: Int, bytesSoFar: Int): Int =
- if (chars.isEmpty) nchars
- else {
- val charSize = if (chars.head < 256) 1 else 2
- val newBytesSoFar = bytesSoFar + charSize
- if (newBytesSoFar > maxBytes) nchars
- else loop(chars.tail, nchars + 1, newBytesSoFar)
- }
- val nchars = loop(s.toCharArray, 0, 0)
- s.substring(0, s.length min nchars)
- }
- def dump(s: String, maxBytes: Int) = println(s"$s limited to $maxBytes bytes: ${cutOff(s, maxBytes)}")
- dump("r", 3)
- dump("r", 2)
- dump("r", 1)
- dump("r", 0)
- dump("й", 3)
- dump("й", 2)
- dump("й", 1)
- dump("й", 0)
- }
- /*
- r limited to 3 bytes: r
- r limited to 2 bytes: r
- r limited to 1 bytes: r
- r limited to 0 bytes:
- й limited to 3 bytes: й
- й limited to 2 bytes: й
- й limited to 1 bytes:
- й limited to 0 bytes:
- */
Advertisement
Add Comment
Please, Sign In to add comment