Scala String.codePointCount
Count Unicode code points in valid text, including a supplementary symbol.
A simple example
String.codePointCount
- Start with "A😀"
- Do this Count Unicode code points
- Result 2
object Lesson {
def main(args: Array[String]): Unit = {
val value = "A😀"
println(value.codePointCount(0, value.length))
}
}
2
Syntax
value.codePointCount(0, value.length)
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonCount symbols in an attendance reaction
A student response can combine ordinary letters, accents and emoji. Choose the unit being counted before applying a length limit, because code points and visible symbols do not always line up.
object Lesson {
def main(args: Array[String]): Unit = {
val value = "A😀B"
println(value.codePointCount(0, value.length))
}
}
3
The emoji counts once alongside two ASCII letters.
Count a decomposed accent
A student types an accented letter using a base letter followed by a combining mark. Count the Unicode code points and relate that result to the single accented letter visible on screen.
object Lesson {
def main(args: Array[String]): Unit = {
val value = "é"
println(value.codePointCount(0, value.length))
}
}
2
The base e and combining mark are separate code points.
Read a parcel sorting code
The depot scans a parcel marked NC-17. This identifier uses only ASCII characters. Count all characters, including the separator, to check the scanner’s length field.
What to watch for
A displayed character may contain several code points. Validate the encoding of externally supplied bytes.