Bohtvaroh

Limiting string size in bytes

Dec 13th, 2013
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.99 KB | None | 0 0
  1. import scala.annotation.tailrec
  2.  
  3. object test extends App {
  4.  
  5.   def cutOff(s: String, maxBytes: Int): String = {
  6.     @tailrec
  7.     def loop(chars: Seq[Char], nchars: Int, bytesSoFar: Int): Int =
  8.       if (chars.isEmpty) nchars
  9.       else {
  10.         val charSize = if (chars.head < 256) 1 else 2
  11.         val newBytesSoFar = bytesSoFar + charSize
  12.         if (newBytesSoFar > maxBytes) nchars
  13.         else loop(chars.tail, nchars + 1, newBytesSoFar)
  14.       }
  15.  
  16.     val nchars = loop(s.toCharArray, 0, 0)
  17.     s.substring(0, s.length min nchars)
  18.   }
  19.  
  20.   def dump(s: String, maxBytes: Int) = println(s"$s limited to $maxBytes bytes: ${cutOff(s, maxBytes)}")
  21.  
  22.   dump("r", 3)
  23.   dump("r", 2)
  24.   dump("r", 1)
  25.   dump("r", 0)
  26.   dump("й", 3)
  27.   dump("й", 2)
  28.   dump("й", 1)
  29.   dump("й", 0)
  30. }
  31.  
  32. /*
  33. r limited to 3 bytes: r
  34. r limited to 2 bytes: r
  35. r limited to 1 bytes: r
  36. r limited to 0 bytes:
  37. й limited to 3 bytes: й
  38. й limited to 2 bytes: й
  39. й limited to 1 bytes:
  40. й limited to 0 bytes:
  41. */
Advertisement
Add Comment
Please, Sign In to add comment