Skip to content

Instantly share code, notes, and snippets.

@andrewconner
Created August 16, 2013 16:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewconner/6251536 to your computer and use it in GitHub Desktop.
Save andrewconner/6251536 to your computer and use it in GitHub Desktop.
Trimming a string at a certain number of bytes
import java.nio.{ByteBuffer, CharBuffer}
import java.nio.charset.Charset
def trimAtBytes(str: String, len: Int, charset: Charset) = {
val outBuf = ByteBuffer.wrap(new Array[Byte](len))
val inBuf = CharBuffer.wrap(str.toCharArray())
charset.newEncoder().encode(inBuf, outBuf, true)
new String(outBuf.array, 0, outBuf.position(), charset)
}
val multiByteStr = "これはどのように切り捨てられてしまいます?"
val singleByteStr = "Will this work?"
trimAtBytes(multiByteStr, 10, Charset.forName("UTF-8"))
trimAtBytes(singleByteStr, 10, Charset.forName("UTF-8"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment