How to split strings into characters in Scala

sam picture sam · Feb 19, 2011 · Viewed 49.2k times · Source

For example, there is a string val s = "Test". How do you separate it into t, e, s, t?

Answer

Rex Kerr picture Rex Kerr · Feb 20, 2011

Do you need characters?

"Test".toList    // Makes a list of characters
"Test".toArray   // Makes an array of characters

Do you need bytes?

"Test".getBytes  // Java provides this

Do you need strings?

"Test".map(_.toString)    // Vector of strings
"Test".sliding(1).toList  // List of strings
"Test".sliding(1).toArray // Array of strings

Do you need UTF-32 code points? Okay, that's a tougher one.

def UTF32point(s: String, idx: Int = 0, found: List[Int] = Nil): List[Int] = {
  if (idx >= s.length) found.reverse
  else {
    val point = s.codePointAt(idx)
    UTF32point(s, idx + java.lang.Character.charCount(point), point :: found)
  }
}
UTF32point("Test")