Skip to content

Instantly share code, notes, and snippets.

@ocadaruma
Created May 8, 2017 07:52
Show Gist options
  • Save ocadaruma/3f21d4e22e7f947f82d4c9363a590e2f to your computer and use it in GitHub Desktop.
Save ocadaruma/3f21d4e22e7f947f82d4c9363a590e2f to your computer and use it in GitHub Desktop.
StringOps that handle surrogate pair.
implicit class CodePointOps(val self: String) extends AnyVal {
// take
def takeCodePoints(n: Int): String = {
val itr = java.text.BreakIterator.getCharacterInstance
itr.setText(self)
val codePointCount = Iterator.continually(itr.next()).takeWhile(_ != java.text.BreakIterator.DONE).take(n).size
new String(self.codePoints.toArray, 0, codePointCount)
}
}
// example
"𠀋𡑮".takeCodePoints(1) // => "𠀋"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment